J.P Masangcay
J.P Masangcay

Reputation: 769

Unable to change the Month format for DateTime

I'm trying to Convert a date and time string to DateTime variable also change the month to double digit month instead of a single digit.

Here is my current code:

string date = item; // 6/17/15 10:02:01 AM
DateTime dt = Convert.ToDateTime(item);
string dtm = dt.Month.ToString("MM");
string dty = dt.Year.ToString("yyyy");
Console.WriteLine(date);
Console.WriteLine("Year: {0}, Month: {1}, Day: {2}", dty, dtm, dt.Day);
Console.WriteLine(dt.TimeOfDay);

Upvotes: 2

Views: 122

Answers (3)

Vivek Jain
Vivek Jain

Reputation: 3889

If all you want to do is output the string that you have written in your code, try this:

string date = item; // 6/17/15 10:02:01 AM
DateTime dt = Convert.ToDateTime(item);
Console.WriteLine(dt.ToString("'Year: 'yyyy', Month: 'MM', Day: 'dd"));

Note the use of single quotes in the string

Upvotes: 0

Piotr Stapp
Piotr Stapp

Reputation: 19830

The formatting string in ToString method is available only for DateTime object. So you can just write:

string dtm = dt.ToString("MM");
string dty = dt.ToString("yyyy");

The second option is to simple Tostring method on int objects with leading zeros like:

string dtm = dt.ToString("D2");
string dty = dt.ToString("D2");

Upvotes: 0

Matthew Watson
Matthew Watson

Reputation: 109547

You need:

string dtm = dt.ToString("MM");
string dty = dt.ToString("yyyy");

Your original code is trying to apply custom DateTime formatting to dt.Month, which is just an int and therefore the custom date format strings are not applicable to it. (Same goes for the year).

Upvotes: 1

Related Questions