About Date And Time Handling in Matlab

1 回表示 (過去 30 日間)
Hadi Hajieghrary
Hadi Hajieghrary 2016 年 7 月 26 日
コメント済み: Hadi Hajieghrary 2016 年 7 月 26 日
Hello
There is something wrong with the date and time handling of Matlab 2015b. For example consider this:
>>curTime=datestr([2015 05 18 16 50 00],'HH:MM')
>>datestr(datenum(curTime),'mmmm dd, yyyy HH:MM:SS.FFF AM')
And the answer is "January 01, 2016 4:50:00.000 PM" Why!? Then the answer for the code you write depends on the time you run it? If I run it in 2017 is it going to be "January 01, 2017 4:50:00.000 PM"?
Thanks

回答 (1 件)

Steven Lord
Steven Lord 2016 年 7 月 26 日
What exactly is InitialTime? Is it a typo and it's supposed to be curTime? If so, look at what curTime contains.
>> curTime=datestr([2015 05 18 16 50 00],'HH:MM');
>> whos curTime
Name Size Bytes Class Attributes
curTime 1x5 10 char
Any information about the year, month, or day has been lost by the conversion to a char array -- by the way you constructed it, all curTime lists is hours and minutes.
So what does datenum do if it doesn't have enough information to create a serial date number? The documentation for datenum (this is a link to the current release's documentation, but the part I'm going to quote is the same in release R2015b) says:
Certain formats might not contain enough information to convert text representations of dates and times.
In those cases, hours, minutes, and seconds default to 0, days default to 1, months default to January,
and years default to the current year. datevec and datenum consider two-character years (e.g., '79')
to fall within the 100-year range centered around the current year.
So yes, if you ran that code in 2017 the answer would be "January 01, 2017 4:50:00.000 PM" but not through any fault of datenum or datestr.
Rather than using datestr and datenum, have you considered using datetime? Using datetime you can keep all the information around but change how it is displayed.
>> curTime = datetime(2015, 5, 18, 16, 50, 0, 'Format', 'HH:mm')
>> curTime.Format = 'MMMM dd, yyyy HH:mm:SS.sss a'
Note that some of the letters used in the datetime Format are different than those used by datestr -- see the documentation for the datetime Format property for more information.
  1 件のコメント
Hadi Hajieghrary
Hadi Hajieghrary 2016 年 7 月 26 日
I am so sorry. I just corrected my Question.
Thanks. Hadi

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

カテゴリ

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