[英]Format date time
嘿,我正在提取文件創建的日期和時間。 日期應為2010年7月1日下午2點,但從我的應用程序中調用時,格式為2010年8月1日下午2點08分。 我希望它能像文件瀏覽器中一樣顯示(2010年7月1日下午2:08)。 我該怎么做?
string createdOnCMM = Creationtime; //this returns the 2:08:07 01/07/2010
// I think I need a modified verison of the following to reformat it
DateTime dt = Convert.ToDateTime(createdOnCMM);
String.Format("0:{dd/MM/yyyy HH:mm:ss}", dt);
您的復合格式字符串不太正確。 嘗試這個:
string s = string.Format("{0:dd/MM/yyyy HH:mm:ss}", dt);
或者,如果你只是要格式化的DateTime
,直接調用toString:
string s = dt.ToString("dd/MM/yyyy HH:mm:ss");
(這是一種更具可讀性的方法,IMO。)
請注意,目前這是非常特定於文化的。 這可能是好您的特定用途,但你應該意識到這一點。
從Microsoft的標准日期和時間格式字符串中 ,您應該能夠通過使用g
格式字符串來獲得所需的內容,如下所示:
String.Format("{0:g}", dateTimeValue);
那應該產生您想要的格式。
如果您只需要使用當前區域性的短日期字符串進行格式化,則可以使用Eric的答案中提到的g
指定符。
如果您需要所提到的確切格式,而不考慮您當前的區域性,則可以使用以下方法之一:
string formatted = dt.ToString("M'/'d'/'yyyy h':'mm tt");
// or
string formatted = string.Format("{0:M'/'d'/'yyyy h':'mm tt}", dt);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.