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"
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");
The day of the month. Single-digit days will have a leading zero. The abbreviated name of the day of the week.
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.
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.
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
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");
}
myDate.ToString("dd/MM/yyyy hh:mm:ss tt")
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With