繁体   English   中英

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

[英].NET convert Datetime to format Sortable date/time pattern (“s”);

我正在使用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.")

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

谢谢

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

String date = String.Format("{0:s}", currTime);

这可以缩短一点:

String date = currTime.ToString("s");

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

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

每次在需要将其转换为字符串的地方使用DateTime值时(例如在string.Format() ),C#通常会调用.ToString()方法。 DateTime类型声明了一个具有您不想要的格式的.ToString()方法。

但是, DateTime还有其他方法,包括.ToString(IFormatProvider provider).ToString(string format)

因此,如果将相关类似字符串的上下文中的DateTime变量的每次使用替换为调用相应.ToString重载的变量,则可以实现所需的功能,例如:

代替

var message = string.Format("The parcel was sent on {0}.", currTime);

采用

var message = string.Format("The parcel was sent on {0}.", currTime.ToString("s"));

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM