Adding leading zeros to date time C#

16,166

Solution 1

If you say, that it is both strings, then you should use the DateTime.TryParse method:

DateTime dt;
if (DateTime.TryParse("9/10/2011 9:20:45 AM", out dt))
{
    Console.WriteLine(dt.ToString("dd/MM/yyyy hh:mm:ss tt"));
}
else
{
    Console.WriteLine("Error while parsing the date");
}

Solution 2

DateTime.Now.ToString("dd/MM/yyyy hh:mm:ss tt") // 12hour set
DateTime.Now.ToString("dd/MM/yyyy HH:mm:ss") // 24hour set

More information / methods about formatting Date can be found Here

From you comment

It's better to use the following to parse a DateTime

DateTime date = DateTime.MinValue;
DateTime.TryParse("9/10/2011 9:20:45 AM", out date);
return date.ToString("MM/dd/yyyy hh:mm:ss tt")

You can then check wether it fails by comparing it to DateTime.MinValue rather then crash the application if the Convert.ToDatetime fails

Solution 3

myDate.ToString("dd/MM/yyyy hh:mm:ss tt")

Solution 4

DateTime dt = ...
dt.ToString("dd/MM/yyyy hh:mm:ss tt");

Solution 5

Use string stringVariable = string.Format("{0:dd/MM/yyyy hh:mm:ss tt}", dateTimeVariable);

Share:
16,166
eomeroff
Author by

eomeroff

please delete me

Updated on June 08, 2022

Comments

  • eomeroff
    eomeroff almost 2 years

    What is the best way to add zeros to date time in C#

    Example string "9/10/2011 9:20:45 AM" convert to string "09/10/2011 09:20:45 AM"

    • Amedio
      Amedio almost 13 years
      DO you want to put leading zeros on the DateTime object or on the resultant String of ToString() method of DateTime? Thanks :)
    • eomeroff
      eomeroff almost 13 years
      IT is both strings, I do not use DateTime object
  • user2476101
    user2476101 almost 13 years
    I'll give you a few minutes to fix this before I downvote... hint: months/minutes?
  • eomeroff
    eomeroff almost 13 years
    Because I use only string is this solution ok, DateTime dateTime = Convert.ToDateTime(oldDate); String newDate = dateTime.ToString("MM/dd/yyyy HH:mm:ss tt"); thanks
  • Theun Arbeider
    Theun Arbeider almost 13 years
    @SonOfOmer using "MM/dd/yyyy HH:mm:ss tt" is double. HH shows the 24hour time, so it would show 14 if it's 2pm. The tt also shows PM. It's better to use either hh:mm:ss tt or HH:mm:ss.
  • markus
    markus over 11 years
    Why will it help the OP, why should the OP use this? Explain the advantages of your solution, please!