3

I parse a date that is in string format and would like to convert it to a datetime format but cannot figure out how to do this. The date appears as such;

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

and would like it in a simple form of

2012-04-18 08:00:00 

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

abatishchev
  • 98,240
  • 88
  • 296
  • 433
vbNewbie
  • 3,291
  • 15
  • 71
  • 155

2 Answers2

6
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 parse the date format you provided. Note that that the above format string assumes the date format you're parsing uses two digits for days that are less than 10, ie. April 01.

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

Will produce the desired output date format.

For reference you should look at the MSDN documentation for DateTime.ParseExact() and Custom Date and Time Format Strings.

Dan Rigby
  • 17,133
  • 6
  • 43
  • 60
  • thanks; I tried that before and then used your code exactly and still get the error: string was not recognized as a valid datetime – vbNewbie Apr 18 '12 at 19:54
  • I think you may have leading or trailing white space in your string then. Try passing `dateString.Trim()` into the code and see if it works. I updated my answer to show this. – Dan Rigby Apr 18 '12 at 20:03
  • nevermind figured it out thanks, format was wrong ddd MMM dd hh:mm:ss zzz yyyy and I was removing the + in the first place. Thanks for your help – vbNewbie Apr 18 '12 at 20:10
3
  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);
  }
Luke Hutton
  • 10,612
  • 6
  • 33
  • 58
  • thanks; I tried that before and then used your code exactly and still get the error: string was not recognized as a valid datetime – vbNewbie Apr 18 '12 at 19:52
  • nevermind figured it out thanks, format was wrong ddd MMM dd hh:mm:ss zzz yyyy and I was removing the + in the first place. Thanks for your help – vbNewbie Apr 18 '12 at 20:10