我有以下代码:
string textTransDate = String.Format("{0}-{1}-{2} {3}:{4}", DateTime.Now.Year, DateTime.Now.Month, DateTime.Now.Day, DateTime.Now.Hour, DateTime.Now.Minute);
如果它们小于10,我想在月和日参数中添加前导零,我将如何实现此目标?
答案 0 :(得分:10)
string textTransDate = DateTime.Now.ToString("yyyy-MM-dd HH:mm");
更多信息:
答案 1 :(得分:2)
String.Format(@"{0:yyyy-MM-dd HH\:mm}", DateTime.Now);
转义字符\:确保您将获得一个文字冒号分隔符而不是特定于文化的时间分隔符,以匹配您的原始代码。请参阅Custom Date and Time format strings in MSDN。
要获得数字参数的前导零,请查看Custom Numeric Format Strings:
String.Format("{0:0000}-{1:00}-{2:00} {3:00}:{4:00}", DateTime.Now.Year, DateTime.Now.Month, DateTime.Now.Day, DateTime.Now.Hour, DateTime.Now.Minute);
甚至Standard Numeric Format Strings:
String.Format("{0:D4}-{1:D2}-{2:D2} {3:D2}:{4:D2}", DateTime.Now.Year, DateTime.Now.Month, DateTime.Now.Day, DateTime.Now.Hour, DateTime.Now.Minute);
答案 2 :(得分:1)
D2
格式会添加前导零。
String.Format("{0}-{1:D2}-{2:D2} {3}:{4}", DateTime.Now.Year, DateTime.Now.Month, DateTime.Now.Day, DateTime.Now.Hour, DateTime.Now.Minute);
答案 3 :(得分:1)
string textTransDate = String.Format("{0}-{1:00}-{2} {3}:{4}", DateTime.Now.Year, DateTime.Now.Month, DateTime.Now.Day, DateTime.Now.Hour, DateTime.Now.Minute);
答案 4 :(得分:0)
这不会起作用:
string textTransDate = DateTime.Now.ToString("yy-MM-hh:mm");