Asynchronous
Asynchronous

Reputation: 3977

How to Format or Pad String date with zeros?

I have date values that are formatted like this: 1/1/2015. These are produced by a Web Service which I cannot change:

How do I Format this: 1/1/2015 to 01/01/2015, with the leading zero?

Tried this:

Console.WriteLine(String.Format("{0:[##/##/####]}", "1/1/2015"));

And this:

Console.WriteLine(String.Format("{0:MM/dd/yyyy}", "1/1/2015"));

But I get the same formatted output.

Upvotes: 2

Views: 3050

Answers (3)

Gopalakrishnan
Gopalakrishnan

Reputation: 517

Convert the date string into DateTime then get it as MM/dd/yyyy or whatever format you want.

DateTime.Parse("1/1/2015").ToString("MM/dd/yyyy");

Upvotes: 0

Rahul Tripathi
Rahul Tripathi

Reputation: 172558

You can try like this:

return yourDateTimeValue.ToString("MM/dd/yyyy");

Edit:

Since you are storing your date as string then try like this:

string s = "1/1/2015";
DateTime dt = 
    DateTime.ParseExact(s, "MM/dd/yyyy", CultureInfo.InvariantCulture);

Upvotes: 1

Soner Gönül
Soner Gönül

Reputation: 98830

I have date values that are formatted like this

In .NET, a DateTime does not have any implicit format. It just have date and time values. Textual representation (aka string representation) of a DateTime can have a format.

If you have string like that, parse it to Datetime and get it's string representation with dd/MM/yyyy format.

string s = "1/1/2015";
DateTime dt;
if(DateTime.TryParseExact(s, "d/M/yyyy", CultureInfo.InvariantCulture,
                          DateTimeStyles.None, out dt))
{
    dt.ToString("dd/MM/yyyy", CultureInfo.InvariantCulture).Dump(); // 01/01/2015
}

Upvotes: 7

Related Questions