Borrar filtros
Borrar filtros

How do I convert a decimal number of months to a datetime format?

210 visualizaciones (últimos 30 días)
Jake
Jake el 5 de Oct. de 2024
Comentada: Christien el 20 de Oct. de 2024 a las 10:24
I have a vector of several decimal values that represent a number of months after Jan 01, 2020.
(e.g. [9.545563 22.212227])
I need to convert these to dates. I'm unsure of how to do this. The ultimate goal of this is to output the dates within an fprintf statement.
(e.g. "Summer 2021/2022 begins on the 3rd of Dec at 3:51:14 and concludes on the 24th of Feb at 22:03:52")
  3 comentarios
JACOB
JACOB el 10 de Oct. de 2024 a las 11:36
Bros cooked for the assignment
Christien
Christien el 20 de Oct. de 2024 a las 10:24
To be honest all of us are cooked

Iniciar sesión para comentar.

Respuestas (2)

Stephen23
Stephen23 el 6 de Oct. de 2024
Editada: Stephen23 el 6 de Oct. de 2024
"The only way I can think of is manually converting by identifying the length of the month the offset represents."
Let MATLAB do that for you:
V = [9.545563,22.212227];
W = fix(V);
X = mod(V,1);
A = datetime(2020,W+1,1);
D = A + X.*(datetime(2020,W+2,1)-A)
D = 1x2 datetime array
17-Oct-2020 21:53:55 07-Nov-2021 08:48:12
For most of those date formats you could download my function DATESTR8601:
[y,d,m,t] = datestr8601(D(1),'y','d*','mmm','*HMS')
y = '2020'
d = '17th'
m = 'Oct'
t = '21:53:55'
[y,d,m,t] = datestr8601(D(2),'y','d*','mmm','*HMS')
y = '2021'
d = '7th'
m = 'Nov'
t = '08:48:12'

Walter Roberson
Walter Roberson el 5 de Oct. de 2024
decmonths = [9.545563 22.212227];
offsets = calmonths(floor(decmonths)) + days(decmonths - floor(decmonths))
offsets = 1x2 calendarDuration array
9mo 13h 5m 36.643s 1y 10mo 5h 5m 36.413s
base = datetime('Jan-01, 2020', 'InputFormat', 'MMM-dd, yyyy')
base = datetime
01-Jan-2020
base + offsets
ans = 1x2 datetime array
01-Oct-2020 13:05:36 01-Nov-2021 05:05:36
Getting the correct output format of "3rd" and "24th" is more difficult. There are no standard routines that will correctly produce that format. (Perhaps there are Java routines for it; I do not know.)
  4 comentarios
Walter Roberson
Walter Roberson el 5 de Oct. de 2024
@Voss is right, I messed up the fractions of a month. Unfortunately, I am having trouble coming up with the correct formula .
Jake
Jake el 6 de Oct. de 2024
The only way I can think of is manually converting by identifying the length of the month the offset represents.

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

R2024a

Community Treasure Hunt

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

Start Hunting!

Translated by