How do I convert a decimal number of months to a datetime format?
조회 수: 35 (최근 30일)
이전 댓글 표시
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
답변 (2개)
Stephen23
2024년 10월 6일
편집: Stephen23
2024년 10월 6일
"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)
For most of those date formats you could download my function DATESTR8601:
[y,d,m,t] = datestr8601(D(1),'y','d*','mmm','*HMS')
[y,d,m,t] = datestr8601(D(2),'y','d*','mmm','*HMS')
댓글 수: 0
Walter Roberson
2024년 10월 5일
decmonths = [9.545563 22.212227];
offsets = calmonths(floor(decmonths)) + days(decmonths - floor(decmonths))
base = datetime('Jan-01, 2020', 'InputFormat', 'MMM-dd, yyyy')
base + offsets
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
Walter Roberson
2024년 10월 5일
@Voss is right, I messed up the fractions of a month. Unfortunately, I am having trouble coming up with the correct formula .
참고 항목
카테고리
Help Center 및 File Exchange에서 Dates and Time에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!