Transfer hh:mm (Time) into "double"

Hello,
I have written a program, that calculates the cheapest way to charge an EV based on dynamic elctricity prices. As an input the program uses the Arrival and Departure time of the user in 'double'. So if the vehicle arrives at "10:30 am" the arrival parameter is 10,5. It gets even more complicated if the arrival time is e.g. "10:31". The value should then be 10,5166666666..... This is quite cumbersome.
Is there any way to transfer "hh:mm" into a double value?
Greetings
Alex

 Accepted Answer

Stephen23
Stephen23 on 3 Apr 2019
Edited: Stephen23 on 3 Apr 2019
>> str = '10:31';
>> val = [1,1/60]*sscanf(str,'%d:%d')
val = 10.51666666666667

2 Comments

That's exactly what I was searching for, Thank you!
+1 Stephen really an efficient trick!

Sign in to comment.

More Answers (1)

Consider this technique:
rightnow = datetime('now');
midnight = dateshift(rightnow, 'start', 'day');
timeSinceMidnight = rightnow-midnight
hours(timeSinceMidnight)
I used datetime arithmetic in constructing the duration timeSinceMidnight, but you can construct it by calling duration if you want.
d = duration('10:31', 'InputFormat', 'hh:mm')
hours(d)

1 Comment

Something close to Steve Lord's datetime solution is really the right way to do this in general. With simple mods, it can work even if the arrival/departure straddle midnight (or a DST shift, and will easily handle a 12 hr clock.
>> arrive = datetime('10:31 am', 'InputFormat', 'hh:mm a')
arrive =
datetime
08-Apr-2019 10:31:00
>> depart = datetime('12:41 pm', 'InputFormat', 'hh:mm a')
depart =
datetime
08-Apr-2019 12:41:00
>> hours(depart - arrive)
ans =
2.1667
When dealing with time in MATLAB, best to use the time/date tools it provides.
Actually, the whole thing is ill-posed unless one assumes the charging stations close before midnight, or that there's a date portion to the data.

Sign in to comment.

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!