简体   繁体   English

如何将 DateTime 对象转换为 YYMMDD 格式?

[英]How do I convert a DateTime object to YYMMDD format?

Um, probably a really simple question, but I just noticed that I have no idea on how to convert DateTime.Now to the format YYMMDD, so for example today (5. November 2009) would be "091105".嗯,可能是一个非常简单的问题,但我只是注意到我不知道如何将DateTime.Now转换为 YYMMDD 格式,例如今天(2009 年 11 月 5 日)将是“091105”。

I know there are overloads to DateTime.Now.ToString() where you can pass in a format string, but I have not found the right format eg for short year format (09 instead of 2009).我知道DateTime.Now.ToString()有重载,您可以在其中传递格式字符串,但我还没有找到正确的格式,例如短年份格式(09 而不是 2009)。

DateTime.Now.ToString("yyMMdd")

You may also find the following two posts on MSDN useful as they contain a lot of info about DateTime formatting:您可能还会发现 MSDN 上的以下两篇文章很有用,因为它们包含大量有关 DateTime 格式的信息:

Standard Date and Time Format Strings标准日期和时间格式字符串
Custom Date and Time Format Strings自定义日期和时间格式字符串

Another alternative that you can do this is by:您可以执行此操作的另一种选择是:

var formattedDate = string.Format("{0:yyMMdd}", DateTime.Now);

Hope this helps!希望这可以帮助!

The reference for the format string is at MSDN: Custom DateTime Format Specifiers .格式字符串的参考位于MSDN:自定义日期时间格式说明符。

What you are looking for specifically is:您要特别寻找的是:

yy Represents the year as a two-digit number. yy将年份表示为两位数。 If the year has more than two digits, only the two low-order digits appear in the result.如果年份超过两位数,则结果中只会出现两位低位数字。 If the year has fewer than two digits, the number is padded with leading zeroes to achieve two digits.如果年份少于两位数,则用前导零填充该数字以达到两位数。

MM Represents the month as a number from 01 through 12. A single-digit month is formatted with a leading zero. MM将月份表示为从 01 到 12 的数字。一位数月份的格式为前导零。

dd Represents the day of the month as a number from 01 through 31. A single-digit day is formatted with a leading zero. dd将月中的日期表示为 01 到 31 之间的数字。一位数的日期格式为前导零。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM