0

I have date in string format as following

Tue Jun 30 2015 00:00:00 GMT+0530 (India Standard Time)

I want to convert it to DateTime in c#.

I am getting this date from telerik datepicker using javascript.

Twix
  • 392
  • 1
  • 12
  • 38
  • 1
    possible duplicate of [Converting a String to DateTime](http://stackoverflow.com/questions/919244/converting-a-string-to-datetime) – Sayse Jul 22 '15 at 06:45

1 Answers1

0

Since your string has UTC offset, I would parse it to DateTimeOffset instead. And there is no way to parse your GMT and (India Standard Time) parts without using literal string delimiter. Remember, neither DateTime nor DateTimeOffset are timezone aware. DateTimeOffset is little bit better at least since this knows about a UTC instant and an offset from that.

var s = "Tue Jun 30 2015 00:00:00 GMT+0530 (India Standard Time)";
DateTimeOffset dto;
if (DateTimeOffset.TryParseExact(s, "ddd MMM dd yyyy HH:mm:ss 'GMT'K '(India Standard Time)'", 
                                 CultureInfo.InvariantCulture, 
                                 DateTimeStyles.None, out dto))

{
     Console.WriteLine(dto);
}

Now you have a DateTimeOffset as {30.06.2015 00:00:00 +05:30}

As an alternative (and better option), Nodatime has ZonedDateTime structure which is;

A LocalDateTime in a specific time zone and with a particular offset to distinguish between otherwise-ambiguous instants.

Soner Gönül
  • 97,193
  • 102
  • 206
  • 364
  • Do I need to use different delimiter for different culture? – Twix Jul 22 '15 at 06:56
  • @Twix What delimiter you are talking about exactly? Since your string has `:` as a `TimeSeparator`, the culture need to have it as well. – Soner Gönül Jul 22 '15 at 07:00
  • How this solution will work for different timezone. I mean `GMT` and `India Standard Time)` this may depend on the user's culture. – Twix Jul 22 '15 at 07:02
  • @Twix No, it won't I told you, `DateTime` and `DateTimeOffset` are timezone _awareness_. Take a look at NodaTime instead. – Soner Gönül Jul 22 '15 at 07:04
  • ok thanks...but I have to do this in c# only without using any other tool or package – Twix Jul 22 '15 at 07:06