crazyTech
crazyTech

Reputation: 1477

Why is "YYYY-MM-DD HH':'MM':'SS" DateTime Format Displaying Incorrectly?

 DateTime timeUtcWhenCommentPostingOccurred = getDateAndTimeOfCommentPostingInUtc();
 DateTime estTime = TimeZoneInfo.ConvertTimeFromUtc(timeUtcWhenCommentPostingOccurred, estZone);


 estTime.ToString("YYYY-MM-DD HH':'MM':'SS");

The above specified format shows the following Incorrect date format :

YYYY-11-DD 21:11:SS

Why does the year, day and second fail to show up properly? Please provide suggestions as to how I can fix the issue above.

Upvotes: 6

Views: 23042

Answers (6)

Habib
Habib

Reputation: 223392

  • Because its lower case y for Year, not upper case Y.
  • Same is the case with Day, its lower case d not upper case D
  • With Minutes its lower case m not upper case M, upper case M is for month,
  • For seconds it lower case s, not upper case S
  • Also remove the single quote in your format, since you don't want to escape string literals

See:Custom Date and Time Format Strings

So your format should be:

estTime.ToString("yyyy-MM-dd HH:mm:ss");

Upvotes: 14

Nogard
Nogard

Reputation: 1789

For full reference check this MSDN article. Try:

estTime.ToString("yyyy-MM-dd HH':'mm':'ss");

Upvotes: 1

recursive
recursive

Reputation: 86144

You got the case wrong:

estTime.ToString("yyyy-MM-dd HH':'mm':'ss");

Upvotes: 2

Rahul Tripathi
Rahul Tripathi

Reputation: 172588

Try this:

estTime.ToString("yyyy-MM-dd HH:mm:ss");

C# is case sensitive and format strings are case sensitive too

Also check this useful MSDN link.

Upvotes: 2

Tim Schmelter
Tim Schmelter

Reputation: 460258

C# is case sensitive and the case has a meaning in datetime format strings.

yyyy is the year, MM the month, dd the day and mm the minute. Uppercase HH means 24h hour clock. This gives the expected output:

string output = estTime.ToString("yyyy-MM-dd HH:mm:ss");

Custom Date and Time Format Strings

Upvotes: 1

D Stanley
D Stanley

Reputation: 152624

Format strings are care-sensitive. YYYY, DD, and SS are not recognized format strings for DateTime, so they are treated as literal characters.

Use

estTime.ToString("yyyy-MM-dd HH:mm:ss");

instead.

Note the distinction between MM (month) and mm (minute).

Upvotes: 3

Related Questions