Dealing with 'Now'
‘Now’ method is commonly used to get the current time. The value returned by the ‘Now’ method is in the current machine time-zone context and cannot be treated as an immutable value.
Converting times to be stored or sent between machines into UTC (Universal Time) is common practice using following method.
DateTime {date} = DateTime.Now.ToUniversalTime();
Resulted value would be off by an hour if called during extra hour occurring during the daylight saving.
Solution is to use ‘UTCNow’
Instead, call the DateTime.UtcNow function directly. This code will always have the proper 24-hour-day perspective, and then be safely converted to local time.
DateTime {timeval} = DateTime.UtcNow;
Not using ‘InvariantCulture’ with DateTime
While dealing with parses method to convert it string date value to DateTime value, it considers machine culture. Issue arises when a developer has an application that runs in any of the culture and have date time conversion in the app.
For example, application has a DateTime picker to show a date with the specific format. In code behind parses a string date to DateTime value using following code snippet.
string {dateString} = "10/1/2016 8:30:52 AM";
DateTime {date} = DateTime.Parse(dateString);
This scenario will generate an unexpected error while dealing with different culture.
Solution is to use ‘InvariantCulture’ method. The following example uses the invariant culture to persist a DateTime value as a string.
//Parse the stored string.
DateTime {dt} = DateTime.Parse("Thur, 1 October 2016 20:34:16 GMT", CultureInfo.InvariantCulture);
It is also easy to parse the string and display its value by using the formatting conventions of the French (France) culture.
// create a French (France) CultureInfo object.
CultureInfo {frFr} = new CultureInfo("fr-FR");
// Displays the date formatted for the "fr-FR" culture.
MessageBox.Show("Date formatted for the " + frFr.Name + " culture: " + dt.ToString("f", frFr));
// Output: Date formatted for the fr-FR culture: mardi 1 octobre 2016 20:34:16
The Parse, ParseExact, TryParse, and TryParseExact methods are used to convert string to its equivalent date and time value.
You can also use DateTime.TryParse Method (String,DateTime) that converts the specified string representation of a date and time to its DateTime equivalent and returns a value that indicates whether the conversion succeeded and does not throw an exception if the conversion fails.