14

I used following functions to convert DateTime from/into string:

DATE_OBJ.ToString(DATE_FORMAT);

DateTime.ParseExact(Date_string, DATE_FORMAT, null);

Now I've got to work with follow format 2012-03-20T14:18:25.000+04:00

Which format should I use to convert it correctly to string and generate string like that from DateTime object?

Stephan Bauer
  • 9,120
  • 5
  • 36
  • 58
Andron
  • 223
  • 1
  • 3
  • 14

4 Answers4

18

You can go from DateTime to that format with

DateTime dt = new DateTime();
dt.ToString("o");

and from that format to DateTime with

DateTimeOffset.Parse(dateString);

Here is some more info on DateTime format: http://www.dotnetperls.com/datetime-format

BvdVen
  • 2,921
  • 23
  • 33
Moriya
  • 7,750
  • 3
  • 35
  • 53
  • 1
    +1: however, I would advise reading MSDN [The Round-trip ("O", "o") Format Specifier](http://msdn.microsoft.com/en-us/library/az4se3k1.aspx#Roundtrip) – horgh Jan 10 '13 at 07:13
9

You are better of using DateTimeOffSet like:

string str = " 2012-03-20T14:18:25.000+04:00";
DateTimeOffset dto = DateTimeOffset.Parse(str);
//Get the date object from the string. 
DateTime dtObject = dto.DateTime; 

//Convert the DateTimeOffSet to string. 
string newVal = dto.ToString("o");
Habib
  • 219,104
  • 29
  • 407
  • 436
4

You cannot do this from DateTime, as DateTime holds no TimeZone info.

This is close: string.Format("{0:s}", dt) will give 2012-03-20T14:18:25. See: http://www.csharp-examples.net/string-format-datetime/

You could extend this to: string.Format("{0:s}.{0:fff}", dt), which will give 2012-03-20T14:18:25.000

But you better have a look at DateTimeOffset: DateTime vs DateTimeOffset

(Not advisable, but to fake it and still use DateTime: string.Format("{0:s}.{0:fff}+04:00", dt))

Community
  • 1
  • 1
Jacco
  • 3,251
  • 1
  • 19
  • 29
-3

If that is a string you receive then you can split the string by T and use only the first part which is the Date component of the whole string and parse that.

ex:

string dateTimeAsString = "2012-03-20T14:18:25.000+04:00";
string dateComponent = dateTimeAsString.Splic('T')[0];
DateTime date = DateTime.ParseExact(dateComponent, "yyyy-MM-dd",null);
dutzu
  • 3,883
  • 13
  • 19