How to convert time format of file date

9 Ansichten (letzte 30 Tage)
Julian Zeitlhöfler
Julian Zeitlhöfler am 13 Mär. 2023
Hello, I want to convert the date string obtained by file.date to the format yyyymmdd_HHMMSS, i.e.,
'13-Mrz-2023 09:19:45'
to
'20230313_091945'.
I want to make the time being UTC and the converion applicable for all system languages (de_DE, en_US, etc.), i.e., system independent.
I'm struggling with the locale parameter ('Mrz' might be 'Mar' in English languages).
The MATLAB version is 2017b.
Thank you for your help.

Akzeptierte Antwort

Stephen23
Stephen23 am 13 Mär. 2023
Bearbeitet: Stephen23 am 13 Mär. 2023
"Hello, I want to convert the date string obtained by file.date to the format yyyymmdd_HHMMSS, i.e.,"
A much simpler and much more robust approach is to use the DATENUM field (assuming that you are working with the output from the DIR function). Then you can trivially avoid all of the hassle of different date locales. For example:
writematrix(pi,'myfile.txt')
S = dir('*.txt') % Use the DATENUM field, not the locale-dependent DATE field!
S = struct with fields:
name: 'myfile.txt' folder: '/users/mss.system.eZW9Qf' date: '13-Mar-2023 09:26:30' bytes: 17 isdir: 0 datenum: 7.3896e+05
T = datetime(S(1).datenum, 'ConvertFrom','datenum', 'Format','uuuuMMdd_HHmmss', 'TimeZone','local')
T = datetime
20230313_092630
T.TimeZone = 'Z' % UTC
T = datetime
20230313_092630
Apparently this forum uses UTC, but if your locale is set up correctly, then changing the TimeZone will adjust the time&date automatically.
  1 Kommentar
Julian Zeitlhöfler
Julian Zeitlhöfler am 13 Mär. 2023
Hi Stephen, thank you very much for the quick and convenient answer.

Melden Sie sich an, um zu kommentieren.

Weitere Antworten (0)

Kategorien

Mehr zu Dates and Time finden Sie in Help Center und File Exchange

Produkte


Version

R2017b

Community Treasure Hunt

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

Start Hunting!

Translated by