How to convert a DateTime object to YYMMDD format?

The mind is probably a very simple question, but I just noticed that I have no idea how to convert DateTime.Now to YYMMDD format, for example today (5. November 2009) will be "091105".

I know there are overloads in DateTime.Now.ToString () where you can pass the format string, but I did not find the correct e format. for the short format of the year (09 instead of 2009).

+7
c #
source share
3 answers
DateTime.Now.ToString("yyMMdd") 

You can also find the following two messages on MSDN, as they contain a lot of DateTime formatting information:

Standard Date and Time Format Strings
Custom Date and Time Format Strings

+15
source share

The format string link is located on MSDN: user-defined date format specifications .

What you are looking for is:

yy Represents the year as a two-digit number. If a year has more than two digits, the result is only two low order digits. If there are less than two digits in a year, the number is filled with leading zeros to achieve two digits.

MM Represents a month as a number from 01 to 12. A one-month month is formatted with a zero value.

dd Represents the day of the month as a number from 01 to 31. A one-day day is formatted with a zero value.

+2
source share

Another alternative you can do is:

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

Hope this helps!

+2
source share

All Articles