Converting a string to a datetime array for the 29th February
Mostrar comentarios más antiguos
When I enter the following code:
a = 'Feb 29 08:59:21';
t = datetime(a,'InputFormat','MMM dd HH:mm:ss');
I receive an error:
-------------------------------
Error using datetime (line 635)
Unable to convert 'Feb 29 08:59:21' to datetime using the format 'MMM dd HH:mm:ss'. If the date/time text contains day, month, or time zone names in a
language foreign to the 'en_US' locale, those might not be recognized. You can specify a different locale using the 'Locale' parameter.
-------------------------------
If I use:
a = 'Feb 28 08:59:21';
t = datetime(a,'InputFormat','MMM dd HH:mm:ss');
This works fine.
I assume this has something to do with there being no year specified and the 29th February only happening on a leap year?
Michael.
5 comentarios
Stephen23
el 13 de Dic. de 2022
"I assume this has something to do with there being no year specified and the 29th February only happening on a leap year?"
Probably.
What year do you expect that datetime object to use, if you do not provide it with a year?
Jiri Hajek
el 13 de Dic. de 2022
Hint: try to remove the semicolon on your second line of your successully working code, to see the value.
t = datetime(a,'InputFormat','MMM dd HH:mm:ss')
You will see that MATLAB implicitly assumes the date is within the current year.
Michael Daly
el 13 de Dic. de 2022
Michael, the error msg you got is correct, but not all that helpful. We are definitely aware of that, and it will improve at some point.
Also, notice that while
% datetime("29-Feb-2022")
is an error,
datetime(2022,2,29)
is not. Why is that? Because you'd want
t = datetime(2022,2,1:60);
t([1 end])
to work. That has a legitimate use case. There's no legitimate use for "29-Feb-2022", no software should ever be creating that timestamp for import into MATLAB.
Michael Daly
el 14 de Dic. de 2022
Respuestas (1)
Dongyue
el 15 de Dic. de 2022
0 votos
If you do not specify the year, MATLAB will automatically view it as the current year. Since 2022 is not a leap year, you will get an error if you want to use datetime for Feb 29th.
Categorías
Más información sobre Dates and Time en Centro de ayuda y File Exchange.
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!