There are two patterns that we can use in SimpleDateFormat to display time. Pattern “hh:mm aa” and “HH:mm aa”, here HH is used for 24 hour format without AM/PM and the hh is used for 12 hour format with AM/PM. aa – AM/PM marker.
ToString() Converts the value of the current DateTime object to its equivalent string representation using the formatting conventions of the current culture.
Use HH
for 24 hour hours format:
DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")
Or the tt
format specifier for the AM/PM
part:
DateTime.Now.ToString("yyyy-MM-dd hh:mm:ss tt")
Take a look at the custom Date and Time format strings documentation.
With C#6.0 you also have a new way of formatting date when using string interpolation e.g.
$"{DateTime.Now:yyyy-MM-dd HH:mm:ss}"
Can't say its any better, but it is slightly cleaner if including the formatted DateTime in a longer string.
More about string interpolation.
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