user3331923
user3331923

Reputation: 49

how to convert a number into mm:ss format using VBScript

I want to convert a number (less than 3600) in mm:ss format using VBScript. The main issue that i am facing is to add leading zeroes in case i get a single digit.
For example:- while trying to convert 306 in mm:ss format i get the output as 5:6 instead of 05:06.
This is my code..

entered_time = "306"
quotient = entered_time/60
quotient = Int(quotient)
MsgBox quotient
remainder = entered_time Mod 60
MsgBox remainder
time_format = quotient&":"&remainder
msgbox time_format

Thanks for the help in advance.

Upvotes: 2

Views: 5112

Answers (4)

AlexLaforge
AlexLaforge

Reputation: 532

Yes, You can call this function :

'Define Function
Function TimePassed(byVal t1, byVal t2)

    'Using "byVal" is important to not alter your source parameters.

    Dim t : t = DateDiff("s", t1, t2)
    Dim hr, min, sec

    t1=t

    hr=t\3600
    If len(hr)=1 Then hr="0" & hr

    t=t mod 3600
    min=t\60
    If len(min)=1 Then min="0" & min

    sec=t mod 60
    If len(sec)=1 Then sec="0" & sec

    TimePassed = hr & ":" & min & ":" & sec

End Function 'TimePassed


'Code logic : Define dates
Dim startDate : startDate = #2024/11/13 08:22:00#
Dim endDate : endDate = #2024/11/13 10:52:00#

'Code logic : Call Function In Classic ASP
Response.Write TimePassed(startDate, endDate)

'Code logic : Call Function In VBScript
WScript.Echo TimePassed(startDate, endDate)

Upvotes: 0

Hackoo
Hackoo

Reputation: 18827

Try like this ;)

intTotalSecs = 306
MsgBox intTotalSecs & "(s) ===> " & ConvertTime(intTotalSecs),vbinformation,"output time format as hh:mm:ss"
'************************************************************
Function ConvertTime(intTotalSecs)
Dim intHours,intMinutes,intSeconds,Time
intHours = intTotalSecs \ 3600
intMinutes = (intTotalSecs Mod 3600) \ 60
intSeconds = intTotalSecs Mod 60
ConvertTime = LPad(intHours) & " h : " & LPad(intMinutes) & " m : " & LPad(intSeconds) & " s"
End Function
'************************************************************
Function LPad(v) 
 LPad = Right("0" & v, 2) 
End Function
'************************************************************

Upvotes: 3

Ekkehard.Horner
Ekkehard.Horner

Reputation: 38745

If your locale/regional settings are suitable, you just do:

>> setlocale "de-de"
>> secs = 308
>> ts = TimeSerial(0, 0, secs)
>> WScript.Echo FormatDateTime(ts, vbLongTime)
>>
00:05:08

If that's not possible, put some effort in a .NET based format class like this one.

Upvotes: 1

Marcus Müller
Marcus Müller

Reputation: 36337

What about a simple if remainder < 10 ?

Upvotes: 0

Related Questions