You are developing an application that accepts the input of dates from the user. Users enter the date in their
local format. The date entered by the user is stored in a string variable named inputDate. The valid date
value must be placed in a DateTime variable named validatedDate. You need to validate the entered date
and convert it to Coordinated Universal Time (UTC). The code must not cause an exception to be thrown.
Which code segment should you use?
A.
bool validDate = DateTime.TryParse(inputDate,
CultureInfo.CurrentCulture, DateTimeStyles.AdjustToUniversal |
DateTimeStyles.AssumeLocal,
out validatedDate);
B.
bool validDate = DateTime.TryParse(inputDate,
CultureInfo.CurrentCulture, DateTimeStyles.AssumeUniversal, out
validatedDate);
C.
bool validDate = true;
try
{
validatedDate = DateTime.Parse(inputDate);
}
catch
{
validDate = false;
}
D.
validatedDate = DateTime.ParseExact(inputDate, “g”
CultureInfo.CurrentCulture, DateTimeStyles.AdjustToUniversal |
DateTimeStyles.AssumeUniversal);
Explanation:
DateTimeStyles.AdjustToUniversal – Date and time are returned as a Coordinated Universal Time
(UTC). If the input string denotes a local time, through a time zone specifier or AssumeLocal, the date and time
are converted from the local time to UTC. If the input string denotes a UTC time, through a time zone specifier
or AssumeUniversal, no conversion occurs. If the input string does not denote a local or UTC time, no
conversion occurs and the resulting Kind property is Unspecified. This value cannot be used with
RoundtripKind.
DateTimeStyles.AssumeLocal – If no time zone is specified in the parsed string, the string is assumed to
denote a local time. This value cannot be used with AssumeUniversal or RoundtripKind.
http://msdn.microsoft.com/en-us/library/vstudio/91hfhz89(v=vs.110).aspx