Converting time/dates to hours or number

35 ビュー (過去 30 日間)
obstac
obstac 2016 年 9 月 13 日
回答済み: Peter Perkins 2016 年 9 月 15 日
Hi I'm getting difficult to convert time dates to hours so i can set paying in my bill parking program . if i have 2 dates like this
t1 = datestr(datenum(now)); %answer is 13-Sep-2016 16:00:49
t2 = datestr(datenum(now)); %answer is 13-Sep-2016 20:00:14
i want to arithmetic (t2-t1) so i can get variable in hour or number . Please Help , Thanks b4 . I'm using matlab R2008a

採用された回答

Walter Roberson
Walter Roberson 2016 年 9 月 13 日
Do not try to do date arithmetic on datestr . Do date arithmetic on the datenum values. The result will be in days. You can use datevec() or datestr() or plain arithmetic to convert the day difference to whatever form you prefer.
(Side note: now() returns a datenum directly.)
  3 件のコメント
Walter Roberson
Walter Roberson 2016 年 9 月 13 日
t1 = datenum('13-Sep-2016 16:00:49');
t2 = datenum('13-Sep-2016 20:00:14');
time_diff = t2 - t1;
hours = floor(time_diff * 24);
minutes = round(time_diff - hours / 24);
fprintf('%d hours, %d minutes\n', hours, minutes);
obstac
obstac 2016 年 9 月 13 日
thank you sir , it works very well :)

サインインしてコメントする。

その他の回答 (1 件)

Peter Perkins
Peter Perkins 2016 年 9 月 15 日
This doesn't help the OP (sorry obstac) who's using R2008a, but the same calculation using datetime:
>> t1 = datetime('13-Sep-2016 16:00:49')
t1 =
datetime
13-Sep-2016 16:00:49
>> t2 = datetime('13-Sep-2016 20:00:14')
t2 =
datetime
13-Sep-2016 20:00:14
>> time_diff = t2 - t1
time_diff =
duration
03:59:25
>> [h,m,s] = hms(time_diff)
h =
3
m =
59
s =
25

カテゴリ

Help Center および File ExchangeDates and Time についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by