tags:

views:

310

answers:

3

Hi, Is there a standard way in .Net C# to convert a datetime obj to ISO format yyyy-mm-dd hh:mm:ss? Or do I need to do some string manipulation to get the date string?

Any advice appreciated.

+7  A: 

To use the strict ISO8601, you can use the s (Sortable) format string:

 myDate.ToString("s"); // example 2009-06-15T13:45:30

It's a short-hand to this custom format string:

myDate.ToString("yyyy'-'MM'-'dd'T'HH':'mm':'ss");

And of course, you can build your own custom format strings.

More info:

CMS
+5  A: 

There is no standard format for the readable 8601 format. You can use a custom format:

theDate.ToString("yyyy-MM-dd HH':'mm':'ss")

(The standard format "s" will give you a "T" between the date and the time, not a space.)

Guffa
Note that this will use `/` as date separator in places like the US and France (as in `2009/12/16 08:42:16`)
Fredrik Mörk
@Fredrik: No, it won't. If I would have used / in the format then it would have use the culture specific date separator, but - is a literal character and won't be replaced by anything else.
Guffa
@Guffa: you are right, of course. Mixed it up, my bad.
Fredrik Mörk
Nice one Guffa, I appreciate the help.
Chin
+1  A: 

The DataTime::ToString() method has string formatter that can be used to output datetime in any required format. See this for more info: http://msdn.microsoft.com/en-us/library/aa326721(VS.71).aspx

A9S6