datenum resulting in incorrect values

12 views (last 30 days)
Wessel ter Laare
Wessel ter Laare on 13 Apr 2021
Commented: Steven Lord on 13 Apr 2021
Good day,
I am trying to convert a date array imported via an excel template into numeric values using the datenum function. Unfortunately I get inaccurate results.
The format imported is a large array shown as 'dd/MM/yyyy hh:mm:ss'. Example below.
d = '12/04/2021 03:00:13';
A = datenum(d);
B = datenum(d,'dd/MM/yyyy HH:mm:ss');
C = datestr(A);
D = datestr(A,'dd/MM/yyyy HH:mm:ss');
E = datestr(B);
F = datestr(B,'dd/MM/yyyy HH:mm:ss');
I tried two options for datenum, and afterwards try to re-write back to string to check the value. Resulting in the following:
A = 7.3849e+05
B = 7.3814e+05
C = '04-Dec-2021 03:00:13'
D = '04/00/2021 03:12:13'
E = '12-Dec-2020 03:04:13'
F = '12/04/2020 03:12:13'
As you can see all incorrect outcomes.
I did download MatLAB on a new computer and remember that previously somewhere the default settings regarding dates might have been changed to EU settings. That's could be why result C returns MM/dd/yyyy HH:mm:ss format? But I can't find where this can be altered.
Hope someone has a solution.
Rgrds,

Answers (1)

Sean de Wolski
Sean de Wolski on 13 Apr 2021
Please use datetime instead of datenum. If you have an excel date, you can convert directly from that
d = datetime(x, 'ConvertFrom', 'excel')
Or you can use datetime with an explicitly defined date format to avoid these issues above.
  1 Comment
Steven Lord
Steven Lord on 13 Apr 2021
A lot of the operations that you would have performed on the date numbers can be performed on the datetime array instead, sometimes with the exact same syntax and sometimes with only minor modifications.
T = datetime('today');
Christmas = datetime(2021, 12, 25);
daysToChristmas = days(Christmas - T)
daysToChristmas = 256
isItChristmasYet = Christmas == T
isItChristmasYet = logical
0
hasChristmasPassed = Christmas < T
hasChristmasPassed = logical
0

Sign in to comment.

Products

Community Treasure Hunt

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

Start Hunting!