Why Must the TimeZone be Specified for datetime when the Time Zone is Included in the DateString?

16 visualizaciones (últimos 30 días)
Suppose I have a date string
fu = "Mon Mar 3 12:20:40 EST 2025"
fu = "Mon Mar 3 12:20:40 EST 2025"
Converting to datetime causes an error because the TimeZone input is not specified
try
d = datetime(fu,'InputFormat','eee MMM d HH:mm:ss z yyyy')
catch ME
ME.message
end
ans = 'The format 'eee MMM d HH:mm:ss z yyyy' contains a field for time zone offset. When that field is present, you must use the 'TimeZone' input parameter to create the datetime array in a specific time zone. You can then convert that array to be unzoned by setting its 'TimeZone' property to ''.'
Why does TimeZone need to be specified if EST is included in the input?
Specifying the TimeZone then results in a warning, though I'm not sure what the "unexpected results" might be.
d = datetime(fu,'InputFormat','eee MMM d HH:mm:ss z yyyy','TimeZone','EST')
Warning: 'EST' specifies a time zone with a fixed offset from UTC, -05:00. This zone does not follow daylight saving time, and so may give unexpected results. See the datetime.TimeZone property for details about specifying time zones.
d = datetime
03-Mar-2025 12:20:40

Respuestas (1)

Walter Roberson
Walter Roberson el 3 de Mzo. de 2025
fu1 = "Mon Mar 3 12:20:40 EST 2025";
d1 = datetime(fu1,'InputFormat','eee MMM d HH:mm:ss z yyyy','TimeZone','-05:00')
d1 = datetime
03-Mar-2025 12:20:40
d2 = datetime(fu1,'InputFormat','eee MMM d HH:mm:ss z yyyy','TimeZone','GMT')
d2 = datetime
03-Mar-2025 17:20:40
fu2 = "Mon Mar 3 12:20:40 CST 2025";
d3 = datetime(fu2,'InputFormat','eee MMM d HH:mm:ss z yyyy','TimeZone','-05:00')
d3 = datetime
03-Mar-2025 13:20:40
So the specified timezone in the datetime input has an effect on the output time.
And the TimeZone that is specified tells datetime() what the output timezone is to be.
  2 comentarios
Paul
Paul el 3 de Mzo. de 2025
Why doesn't TimeZone of d just default to the time zone in the input string?
Seems to me that if the input string contains a time zone, then that's the time zone the user wants absent any other action (like specifying TimeZone).
Mark
Mark el 15 de Abr. de 2025
I'm wondering the same thing. It seems like the TimeZone of the datetime object should be assigned to the zone specified in the input string. As it is, it seems like there is no simple way to preserve this information from the input, as the forced conversion to another zone results in a loss of the data.

Iniciar sesión para comentar.

Categorías

Más información sobre Dates and Time en Help Center y File Exchange.

Etiquetas

Productos


Versión

R2024b

Community Treasure Hunt

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

Start Hunting!

Translated by