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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1679667/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-06 19:57:13  来源:igfitidea点击:

How do I convert a DateTime object to YYMMDD format?

c#stringdatetimeformattingformat

提问by Max

Um, probably a really simple question, but I just noticed that I have no idea on how to convert DateTime.Nowto 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 e.g. for short year format (09 instead of 2009).

我知道DateTime.Now.ToString()您可以在格式字符串中传递重载,但我还没有找到正确的格式,例如短年份格式(09 而不是 2009)。

采纳答案by Dave Downs

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

标准日期和时间格式字符串
自定义日期和时间格式字符串

回答by Guffa

The reference for the format string is at MSDN: Custom DateTime Format Specifiers.

格式字符串的参考位于MSDN:自定义日期时间格式说明符。

What you are looking for specifically is:

您要特别寻找的是:

yyRepresents the year as a two-digit number. 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.

yy将年份表示为两位数。如果年份超过两位数,则结果中只会出现两位低位数字。如果年份少于两位数,则用前导零填充该数字以达到两位数。

MMRepresents the month as a number from 01 through 12. A single-digit month is formatted with a leading zero.

MM将月份表示为从 01 到 12 的数字。一位数月份的格式为前导零。

ddRepresents 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 之间的数字。一位数的日期格式为前导零。

回答by mallows98

Another alternative that you can do this is by:

您可以执行此操作的另一种选择是:

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

Hope this helps!

希望这可以帮助!