[英]Convert DateTime to custom Date format
我有一個DateTime
對象,其值為2011-08-11T01:03:29+00:00
,它是從數據庫返回的。
如何將其轉換為mm/dd/yyyy
格式,因為最終結果類型應該只是DateTime
對象,而不是字符串?
DateTime
對象只是日期的數字表示,從常量開始時間(例如,0000年1月1日)開始為“ticks”。 它不是字符串表示。 要獲取字符串表示形式,請對該對象執行ToString()
。
要將DateTime轉換為自定義格式的字符串,請使用
myDateTime.ToString("MM/dd/yyyy");
有關DateTime.ToString()
自定義格式的完整詳細信息,請參見http://msdn.microsoft.com/en-us/library/8kb3ddd4.aspx 。
請參閱http://msdn.microsoft.com/en-us/library/system.datetime.aspx :
“在內部,所有DateTime值都表示為自0001年1月1日午夜12:00:00起經過的刻度數(100納秒間隔的數量)。實際的DateTime值與該方式無關。當在用戶界面元素中顯示或寫入文件時,將顯示值。“
將其作為字符串傳遞並解析它
format = "mm/dd/yyyy";
try {
result = DateTime.ParseExact(yourDate.ToString(format), format, provider);
}
catch (FormatException) {
Console.WriteLine("{0} is not in the correct format.", dateString);
}
DateTime有一個叫ToLongDateString(
)和ToShortDateString()
函數(我相信那些是正確的函數名),而short函數就是你想做的。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.