Syntax formatting difficult to convert

I am parsing a date that is in a string format and would like to convert it to a date and time format, but I cannot figure out how to do this. The date is displayed as such;

Wed April 18 08:00:04 +08:00 2012

and would like in a simple way

2012-04-18 08:00:00 

the code:

Dim postDate As DateTime
Dim provider As CultureInfo = CultureInfo.InvariantCulture

contentDate = Regex.Replace(contentDate, "\+", "")
Dim format As String = "ddd MMMM dd HH:mm:ss zzz yyyy"
postDate = DateTime.ParseExact(contentDate, format, provider)
contentDate = postDate.ToString("yyyy-MM-dd hh:mm:ss tt")

any ideas appreciated

+3
source share
2 answers
var format = "ddd MMMM dd H:mm:ss zzz yyyy";
var culture = System.Globalization.CultureInfo.InvariantCulture;
DateTime date = DateTime.ParseExact(dateString.Trim(), format, culture);

Will analyze the date format you provided. Please note that the above formatted string assumes that the date format you are processing uses two digits for days that are less than 10, i.e. April 01.

date.ToString("yyyy-MM-dd hh:mm:ss tt");

Will produce the desired output date format.

MSDN DateTime.ParseExact() .

+6
  string dateString, format;  
  DateTime result;
  CultureInfo provider = CultureInfo.InvariantCulture;

  dateString = "Wed April 18 08:00:04 +08:00 2012";
  format = "ddd MMMM dd HH:mm:ss zzz yyyy";
  try {
     result = DateTime.ParseExact(dateString, format, provider);
     Console.WriteLine("{0} converts to your format {1}.", dateString, 
        result.ToString("yyyy-MM-dd HH:mm:ss"));
  }
  catch (FormatException) {
     Console.WriteLine("{0} is not in the correct format.", dateString);
  }
+3

All Articles