Parse a string with time zone information to DateTime in CSharp
Description
The following code shows how to parse a string with time zone information to DateTime.
Example
// ww w. j ava2 s . c om
using System;
using System.Globalization;
public class Example
{
public static void Main()
{
CultureInfo enUS = new CultureInfo("en-US");
string dateString;
DateTime dateValue;
// Parse a string with time zone information.
dateString = "05/01/2009 01:30:42 PM -05:00";
try {
dateValue = DateTime.ParseExact(dateString, "MM/dd/yyyy hh:mm:ss tt zzz", enUS, DateTimeStyles.None);
Console.WriteLine("Converted '{0}' to {1} ({2}).", dateString, dateValue,
dateValue.Kind);
}
catch (FormatException) {
Console.WriteLine("'{0}' is not in an acceptable format.", dateString);
}
// Allow a leading space in the date string.
try {
dateValue = DateTime.ParseExact(dateString, "MM/dd/yyyy hh:mm:ss tt zzz", enUS,
DateTimeStyles.AdjustToUniversal);
Console.WriteLine("Converted '{0}' to {1} ({2}).", dateString, dateValue,
dateValue.Kind);
}
catch (FormatException) {
Console.WriteLine("'{0}' is not in an acceptable format.", dateString);
}
}
}
The code above generates the following result.