views:

843

answers:

7
+2  Q: 

Date format c#

Can I get DateTime.Now to be formatted to

2010-03-01T00:00:00Z

I have used this to format the date part

DateTime.Now.Subtract(new TimeSpan(3001, 0, 0, 0)).GetDateTimeFormats()[5]
+4  A: 

Yes if you use ToString, have a look at the MSDN page for datetime formatting:

http://msdn.microsoft.com/en-us/library/8kb3ddd4.aspx

Adam
+2  A: 

I guess you want this:

 XmlConvert.ToString(yourdate)
Lucero
This gives the same as .ToString("o") which could be 2009-06-11T17:11:10.5312500+0100 which may or may not be what the OP wanted.
Martin Brown
If you wanted to force UTC you could use this XmlConvert.ToString(DateTime.Now, XmlDateTimeSerializationMode.Utc)
Martin Brown
A: 
DateTime.Now.Subtract(new TimeSpan(3001, 0, 0, 0)).ToString("s");

Heres a list of ways to format a string

Brandon
This does not put the Z at the end.
Martin Brown
A: 

For all your C# string/date formatting needs: http://blog.stevex.net/index.php/string-formatting-in-csharp/

I see:

s   Sortable date string  2002-12-10T22:11:29
u   Universal sortable, local time  2002-12-10 22:13:50Z

But given the options on the page you can construct the precise format manually.

blu
+1  A: 

.ToString("yyyy-MM-ddTHH:mm:ssZ")

eschneider
+2  A: 

Very simple, just use a format string that fits your requirements:

System.DateTime.Now.ToUniversalTime().ToString("yyyy-MM-ddTHH:mm:ssZ")
'2009-06-11T16:26:47Z'
gimel
+1 for remembering to call ToUniversalTime.
Martin Brown
+2  A: 

All the following examples assume that local time is London time and it is 5:11pm on the 11th June 2009.

If you want full ISO 8601 format you can use:

DateTime.Now.ToUniversalTime().ToString("o")
// Gives 2009-06-11T16:11:10.5312500Z

Or this if you want to specify a time zone offset:

DateTime.Now.ToString("o")
// Gives 2009-06-11T17:11:10.5312500+0100

If you don't want the fraction of a second you can use this:

DateTime.Now.ToUniversalTime().ToString("s") + "Z"
// Gives 2009-06-11T16:11:10Z

or:

DateTime.Now.ToUniversalTime().ToString("yyyy-MM-ddTHH:mm:ssK")
// Also gives 2009-06-11T16:11:10Z

Note that the following is wrong as it gives the local time as though it is UTC time which is only true if you are somewhere like London and it is the middle of winter:

DateTime.Now.ToString("yyyy-MM-ddTHH:mm:ssZ")
// Gives 2009-06-11T17:11:10Z which is wrong as it is an hour out.
Martin Brown