BMBM
BMBM

Reputation: 16013

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".

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).

Upvotes: 17

Views: 39216

Answers (3)

mallows98
mallows98

Reputation: 1539

Another alternative that you can do this is by:

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

Hope this helps!

Upvotes: 5

Guffa
Guffa

Reputation: 700152

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

What you are looking for specifically is:

yy Represents 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.

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

dd Represents the day of the month as a number from 01 through 31. A single-digit day is formatted with a leading zero.

Upvotes: 2

Dave D
Dave D

Reputation: 8972

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:

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

Upvotes: 29

Related Questions