.NET将Datetime转换为格式可排序的日期/时间模式("s");

And*_*lez 3 .net c# format datetime

我正在使用VS2008,.NET和C#,我需要向我们的客户发送一个DATETIME变量.

问题是他们希望Date以可排序日期/时间模式("s")的格式.

当我得到实际的日期时间时,它是一个Datetime对象.当我将其格式化为给定格式时,现在是一个String对象,它具有我想要的格式.但之后我无法使用相同格式的格式化String创建Datetime对象,因为它始终将其返回到原始Datetime格式.

更加具体:

DateTime currTime = System.DateTime.Now; //(the format is "13/08/2010 09:33:57 a.m.")

String date = String.Format("{0:s}", currTime);// (wanted format "2010-08-13T09:33:57")

DateTime newDate = DateTime.Parse(date);// (original format again "13/08/2010 09:33:57 a.m.")

IFormatProvider culture = new System.Globalization.CultureInfo("", true); //(Invariant Culture)
String format = "s";                        
DateTime fecha = DateTime.ParseExact(date, format, culture); // (original format again "13/08/2010 09:33:57 a.m.")
Run Code Online (Sandbox Code Playgroud)

有没有办法获得具有所需格式的Datetime对象,或者Datetime对象使用给定的格式,并且您不能将它们格式化为等效的字符串格式?

谢谢

Jam*_*ran 10

A DateTime只是一个数字.它没有内在的"格式".它只在转换为字符串时呈现为格式.因此,每当您需要将DateTime作为字符串时,您必须指定所需的格式.

String date = String.Format("{0:s}", currTime);
Run Code Online (Sandbox Code Playgroud)

这可以缩短一点:

String date = currTime.ToString("s");
Run Code Online (Sandbox Code Playgroud)

  • 嗯..我键入`DataTime`*两次*?? 看看当我没有Intellisense时会发生什么...... (2认同)

fea*_*net 5

如果我正确理解了这个问题,我认为你会感到困惑.一个DateTime对象本身不是可格式化的,它本质上只是一个数值(自DateTime.MinValue那以来的刻度数或其他值).

您可以将DateTime对象转换为您喜欢的任何格式的string 表示,但您不会更改实际DateTime对象.