Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding leading zeros to date time C#

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"

like image 208
eomeroff Avatar asked May 20 '11 08:05

eomeroff


People also ask

How do you add leading zeros to a number in C?

Step 1: Get the Number N and number of leading zeros P. Step 2: Convert the number to string using the ToString() method and to pad the string use the formatted string argument “0000” for P= 4. val = N. ToString("0000");

What is leading zeros in dates?

The day of the month. Single-digit days will have a leading zero. The abbreviated name of the day of the week.

How do you add leading zeros to a string?

The format() method of String class in Java 5 is the first choice. You just need to add "%03d" to add 3 leading zeros in an Integer. Formatting instruction to String starts with "%" and 0 is the character which is used in padding. By default left padding is used, 3 is the size and d is used to print integers.

How can I pad a value with leading zeros?

To pad an integer with leading zeros to a specific length To display the integer as a decimal value, call its ToString(String) method, and pass the string "Dn" as the value of the format parameter, where n represents the minimum length of the string.


3 Answers

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

like image 61
Theun Arbeider Avatar answered Oct 16 '22 16:10

Theun Arbeider


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");
}
like image 29
VMAtm Avatar answered Oct 16 '22 17:10

VMAtm


myDate.ToString("dd/MM/yyyy hh:mm:ss tt")
like image 44
mathieu Avatar answered Oct 16 '22 17:10

mathieu