Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add leading zero to time using VB.NET?

Tags:

vb.net

In the code below, I'm using the current date and time, with the help of which I am generating a file name. My problem is that it's giving me an output without leading zeros:

Dim strDateTime As String = DateTime.Now.Day.ToString() & "" & _ 
DateTime.Now.Month.ToString() & "" & DateTime.Now.Year.ToString() & "" & _ 
DateTime.Now.Hour.ToString() & "" & DateTime.Now.Minute.ToString() & "" & _
DateTime.Now.Second.ToString() & DateTime.Now.Millisecond.ToString()

For example, my query is giving output as below currently:

Assume time is 1:5:30 :: hh:mm:ss

Required output is: 01:05:30

How can I achieve this?

like image 527
user1494292 Avatar asked Nov 05 '25 04:11

user1494292


1 Answers

Try this,

DateTime.Now.Hour.ToString("00") & ":" & DateTime.Now.Minute.ToString("00") & ":" & DateTime.Now.Second.ToString("00")

EDIT :

As suggested by 'mdb' in the answers, using Custom Date and Time Format Strings would be more efficient and cleaner

DateTime.Now.ToString("hh:mm:ss tt") '12 Hour format with AM/PM designator, Eg :- 09:01:01 PM
DateTime.Now.ToString("HH:mm:ss") '24 Hour format  Eg :- 21:01:01
like image 65
Nalaka526 Avatar answered Nov 07 '25 14:11

Nalaka526



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!