[英]convert DateTime to string according to customCultureInfo in G((combination of date and Time) format
[英].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.