[英]C# - Date/Time Formatting
Using C#, I am trying to format a date in to the following string format: YYYYMMDD_HHMM.xlsx 使用C#,我试图将日期格式化为以下字符串格式:YYYYMMDD_HHMM.xlsx
Here is my code: 这是我的代码:
DateTime.Today.AddDays(0).ToString("yyyymmdd") + "_" + DateTime.Today.AddDays(0).ToString("hhmm")
Here is my output: 这是我的输出:
20130027_1200.xlsx
Month is not correct, nor is the time. 月份不正确,时间也不正确。
You're using mm
, which is minutes, not months - and you're trying to print the time using DateTime.Today
, which always returns midnight at the start of the day. 你使用
mm
,这是几分钟,而不是几个月 - 而你正在尝试使用DateTime.Today
打印时间 ,它总是在一天开始时返回午夜。
It's not clear why you're adding 0 days, either. 目前尚不清楚你为什么要加0天。 I'd use:
我用的是:
DateTime now = DateTime.Now;
string name = now.ToString("yyyyMMdd'_'HHmm'.xlsx'");
(The '
quoting for the _
isn't strictly necessary, but personally I find it simplest to take the approach of quoting everything that isn't a format specifier.) (
'
引用_
不是绝对必要的,但我个人觉得最简单的方法就是引用一些不是格式说明符的方法。)
Or: 要么:
DateTime now = DateTime.Now;
string name = string.Format("{0:yyyyMMdd}_{0:HHmm}.xlsx", now);
Note the use of HH
instead of hh
to get a 24-hour clock rather than 12-hour, too. 注意使用
HH
而不是hh
来获得24小时制而不是12小时制。
Additionally, consider using UtcNow
instead of Now
, depending on your requirements. 另外,根据您的要求,考虑使用
UtcNow
而不是Now
。 Note that around daylight saving transitions, the clock will go back or forward, so you could end up with duplicate file names. 请注意,围绕夏令时转换,时钟将返回或转发,因此您最终可能会出现重复的文件名。
Also note how in my code I've used DateTime.Now
once - with your original code, you were finding the current date twice, which could have given different results on each invocation. 还要注意我的代码中我是如何使用
DateTime.Now
一次 - 使用原始代码,您发现两次当前日期,这可能会在每次调用时给出不同的结果。
Finally, you might also want to specify CultureInfo.InvariantCulture
when you format the date/time - otherwise if the current culture is one which doesn't use a Gregorian calendar by default, you may not get the results you were expecting. 最后,您可能还希望在格式化日期/时间时指定
CultureInfo.InvariantCulture
- 否则,如果当前文化是默认情况下不使用公历的文化,则可能无法获得您期望的结果。
DateTime.Today
returns DateTime
with all time-related properties set to 0. Use DateTime.Now
instead. DateTime.Today
返回DateTime
其中所有与时间相关的属性都设置为0.请改用DateTime.Now
。
Property value
适当的价值
An object that is set to today's date, with the time component set to 00:00:00.
设置为今天日期的对象,时间组件设置为00:00:00。
Use MM
in your format to get month. 使用您的格式的
MM
来获得月份。 mm
returns minutes. mm
返回分钟。 You can check all format specifiers on MSDN: Custom Date and Time Format Strings 您可以检查MSDN上的所有格式说明符: 自定义日期和时间格式字符串
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.