0

In a string variable I have date in following format : Tue Jul 23 00:00:00 UTC+0530 2013

I tried to convert it into a datetime variable , and got invalid date time error.

DateTime dt = DateTime.Parse(t);

How can I convert into a DateTime format?

Soner Gönül
  • 97,193
  • 102
  • 206
  • 364
TBA
  • 1,077
  • 5
  • 41
  • 80

2 Answers2

9

Use DateTime.ParseExact and use custom format string:

var input = "Tue Jul 23 00:00:00 UTC+0530 2013";
var format = "ddd MMM dd HH:mm:ss UTCzzz yyyy";

DateTime dt = DateTime.ParseExact(input, format, System.Globalization.CultureInfo.InvariantCulture);
MarcinJuraszek
  • 124,003
  • 15
  • 196
  • 263
  • 1
    _Hmm_, but Marcin this prints 22 July? – Soner Gönül Jul 11 '13 at 08:31
  • 1
    @SonerGönül Yes, but that's probably because of your local timezone (which is not +530, is it?). `DateTime` and timezones is a still a bit confusing topic for me, but I would say that's the reason. – MarcinJuraszek Jul 11 '13 at 08:31
  • 2
    Yeah, mine is _UTC+2_ so that could be the reason. _DateTime and timezones is a still a bit confusing topic for me_ Me neither but [I think this is good for us :)](https://twitter.com/joshsusser/status/257725572275376128) – Soner Gönül Jul 11 '13 at 08:35
  • Thanks it worked :) Well now I have chrome returning an all new avatar. I should rather look for a common solution!! @SonerGönül perfect status :) – TBA Jul 11 '13 at 10:11
2

You can use the following code

string[] formats= { "ddd MMM dd HH:mm:ss UTCzzz yyyy" }
DateTime dateTime = DateTime.ParseExact("Tue Jul 23 00:00:00 UTC+0530 2013", formats, new CultureInfo("en-US"), DateTimeStyles.None);
mck
  • 978
  • 3
  • 14
  • 38