Adding to existing date value
조회 수: 4 (최근 30일)
이전 댓글 표시
Hello Everyone.
I have a 1x1 datetime matrix (variable nam: date_for_entry) containing vaue 03/27/2023. I want to add 5 days to this and get the updated date value.
Using caldays does not update the month. i.e. date_for_exit = date_for_entry + caldays(5) gives me value of 03/01/2023 instead of 04/01/2023.
I tried using addtodate. This gave me correct value, however, converting back to datetime format gave me 03/01/2023. Can someone please help?
Thanks!
답변 (2개)
Stephen23
2023년 4월 20일
편집: Stephen23
2023년 4월 20일
"Using caldays does not update the month"
Yes, it does:
dt = datetime(2023,3,27, 'Format','u-MM-dd')
dt = dt+caldays(5)
Apparently you did something else, but because you did not upload any data or show any code, we cannot debug what you did. Debugging invisible code that runs on non-existent data is challenging. It is much easier when you actually give us enough information to help you.
EDIT: the problem is very easy to replicate, we just need to mix up the months and minutes:
dt = datetime(2023,5,27,1,3,2, 'Format','mm/dd/u') % MINUTES/dayofmonth/year
dt + caldays(5) % these are still MINUTES/dayofmonth/year
@Harsh Trivedi: the problem is very simple: you have imported or defined the DATETIME object incorrectly, most likely by swapping the month and minutes. Solution: fix your DATETIME object, using the FORMATs give here:
Deprecated ADDTODATE cannot fix this. The solution is to fix the cause of the problem.
댓글 수: 2
Steven Lord
2023년 4월 20일
The problem might be in the Format of the datetime.
dt = datetime(2023, 3, 27, 12, 3, 45, 'Format', 'u-mm-dd')
dt2 = dt + calmonths(1)
That addition didn't change the minute data (which is what was used in the Format, as the warning indicates) but it did change the month data as you can see by converting the datetime into its component parts using datevec.
datevec(dt)
datevec(dt2)
If you suppressed the warning that datetime usually issues, using the minute identifier instead of the month identifier (or vice versa) would be easier to overlook.
Stephen23
2023년 4월 20일
편집: Stephen23
2023년 4월 20일
@Steven Lord: yes, I was also wondering about that. After a few seconds experimentation, I came up with an example that demonstrates exactly what the OP observes.
dt = datetime(2023,5,27,1,3,2, 'Format','mm/dd/u')
dt + caldays(5)
VBBV
2023년 4월 20일
편집: VBBV
2023년 4월 20일
d = datetime(2023,3,27, 'Format','u-MM-dd')
d = datetime(addtodate(datenum(d),5,"day"),'ConvertFrom','datenum','Format','u-MM-dd')
If you have tried using addtodate you need to convert to datenum first , then use datetime and convert back to datetime in desired format
댓글 수: 1
VBBV
2023년 4월 20일
May be you have used addtodate incorrectly WITHOUT specifying the number of days as argument in function
참고 항목
카테고리
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!