前导零日期格式 C#
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/461098/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Leading Zero Date Format C#
提问by Chris McKee
I have this function...
我有这个功能...
private string dateConvert(string datDate)
{
System.Globalization.CultureInfo cultEnGb = new System.Globalization.CultureInfo("en-GB");
System.Globalization.CultureInfo cultEnUs = new System.Globalization.CultureInfo("en-US");
DateTime dtGb = Convert.ToDateTime(datDate, cultEnGb.DateTimeFormat);
datDate = dtGb.ToString(cultEnUs.DateTimeFormat.ShortDatePattern);
return datDate;
}
But I want it with the leading zero still on lower digits (1-9) so the date is 11-09-2009 (mm-dd-yyyy)...
但我希望它的前导零仍然在较低的数字 (1-9) 上,所以日期是 11-09-2009 (mm-dd-yyyy)...
Now If I wasn't converting it id use string.Format("{0:d}", dateVar) how do I do this in the conversion?
现在如果我没有转换它 id 使用 string.Format("{0:d}", dateVar) 我如何在转换中做到这一点?
***** Solution *****
Used a slightly modified version of the answer below (i.e. one that would render).
***** 解决方案 *****
使用了以下答案的略微修改版本(即会呈现的版本)。
Convert.ToDateTime(datDate).ToString("MM-dd-yyyy");
采纳答案by Mehrdad Afshari
return dateTimeValue.ToString("MM-dd-yyyy");
回答by Glenn Slaven
Can't you use the string.Format
after you've done the conversion?
string.Format
完成转换后不能使用吗?
ie return string.Format("{0:d}", datDate);
IE return string.Format("{0:d}", datDate);
回答by Matt
I would recommend using the latest C# shorthand (format specifier) for usability and readability's sake:
为了可用性和可读性,我建议使用最新的 C# 速记(格式说明符):
return dateTimeValue:MM-dd-yyyy;
Clean and concise.
干净简洁。