开发者

How can I get this DateTime format in .NET

开发者 https://www.devze.com 2023-04-02 04:17 出处:网络
I\'m trying to format some DateTime into this W3C DateTime format :- Complete date plus hours and minutes:

I'm trying to format some DateTime into this W3C DateTime format :-

Complete date plus hours and minutes:
eg. YYYY-MM-DDThh:mmTZD (eg 1997-07-16T19:20+01:00)

where:
 YYYY = four-digit year
 MM   = two-digit month (01=January, etc.)
 DD   = two-digit day of month (01 through 31)
 hh   = two digits of hour (00 through 23) (am/pm NOT allowed)
 mm   = t开发者_Go百科wo digits of minute (00 through 59)
 ss   = two digits of second (00 through 59)
 s    = one or more digits representing a decimal fraction of a second
 TZD  = time zone designator (Z or +hh:mm or -hh:mm)

I originally had this...

var myDateTime = someDateTime.ToString("s",
    System.Globalization.CultureInfo.InvariantCulture);

But that results in a string of :

2011-08-31T08:46:00

Can anyone help?


You want "o":

var myDateTime = someDateTime.ToString("o",
System.Globalization.CultureInfo.InvariantCulture);


Use the following:

yourDateTime.ToString( "yyyy-MM-ddTHH:mmK", CultureInfo.InvariantCulture );

Here is more than you'll ever want to know on DateTime formats:

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


I believe you want

"yyyy-MM-ddTHH:mmK"

Note:

  • HH rather than hh to be 24 hour
  • K to specify the time zone; this relies on the DateTime.Kind being UTC or local; unspecified will end up with an empty string

You should also use CultureInfo.InvariantCulture to make sure no funky culture information is used. (You could quote the - and : as an alternative, but I'd use the invariant culture to make sure.)


You can format it like this:

someDateTime.ToString("yyyy-MM-dd");

Here's the documentation of the 'standard' supported datetime format strings: http://msdn.microsoft.com/en-us/library/az4se3k1(v=VS.100).aspx


someDateTime.ToUniversalTime().ToString("u");

Will get you pretty close => '2011-09-02 10:22:48Z'. If that isn't good enough, then you can create a custom format string that includes the "T" (see 'Custom Date and Time Format Strings').

0

精彩评论

暂无评论...
验证码 换一张
取 消