determine if a datetime value is on a different day

조회 수: 6 (최근 30일)
Tim
Tim 2025년 3월 3일
댓글: Peter Perkins 2025년 3월 3일
If I have two datetime values, t1 and t2, how can I determine if t2 is on a different, and later, day than t1? The check needs to account for end-of-month and end-of-year rollovers, and the times (hr, min, sec) may not be the same between t1 and t2. I just need to know if they are are different calendar days.
Functions like between and caldiff seem to return a duration, but if that duration is less than 24 hours, this method won't work. For example, two times only 2 minutes apart but accoss a day boundary:
t1 = datetime('2025-03-01 23:59:00')
t1 = datetime
01-Mar-2025 23:59:00
t2 = datetime('2025-03-02 00:01:00')
t2 = datetime
02-Mar-2025 00:01:00
dt = caldiff([t2 t1],'days')
dt = calendarDuration
0d
between(t1,t2,'days')
ans = calendarDuration
0d
datenum would work, but MATLAB is recommending not to use. How can this be done with datetime values and functions?

채택된 답변

Stephen23
Stephen23 2025년 3월 3일
편집: Stephen23 2025년 3월 3일
"Functions like between and caldiff seem to return a duration"
BETWEEN and CALDIFF will not help you. Either use DATESHIFT or the properties of the DATETIME object:
t1 = datetime('2025-03-01 23:59:00')
t1 = datetime
01-Mar-2025 23:59:00
t2 = datetime('2025-03-02 00:01:00')
t2 = datetime
02-Mar-2025 00:01:00
dateshift(t1,'start','day')==dateshift(t2,'start','day')
ans = logical
0
t1.Year==t2.Year && t1.Month==t2.Month && t1.Day==t2.Day
ans = logical
0
  댓글 수: 2
Tim
Tim 2025년 3월 3일
Ah, dateshift. That's a new one. I'm still learning all of the datetime functions. Thanks!
Peter Perkins
Peter Perkins 2025년 3월 3일
There's also this, if you are already doing something else with the time-of-day:
[T,D] = timeofday(DT) also returns the date portions of the values in DT as the datetime array D.
The output argument D is equivalent to dateshift(DT,'start','day').
dt = datetime;
[~,day] = timeofday(dt)
day = datetime
03-Mar-2025

댓글을 달려면 로그인하십시오.

추가 답변 (1개)

Walter Roberson
Walter Roberson 2025년 3월 3일
t1 = datetime('2025-03-01 23:59:00')
t1 = datetime
01-Mar-2025 23:59:00
t2 = datetime('2025-03-02 00:01:00')
t2 = datetime
02-Mar-2025 00:01:00
t2 >= t1 & dateshift(t1, 'start', 'day') == dateshift(t2, 'start', 'day')
ans = logical
0

카테고리

Help CenterFile Exchange에서 Dates and Time에 대해 자세히 알아보기

태그

제품


릴리스

R2023b

Community Treasure Hunt

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

Start Hunting!

Translated by