Round date and hour to the previous 15 minute interval
    11 views (last 30 days)
  
       Show older comments
    
Hello
I would like to round the datetime variable to the previous 15 minutes interval. The tricky part is that it has to be based on the current time. For instance:
t1 = datetime('now','Format','yyyy-MM-dd HH:mm')
the result of the previous code is
2018-03-08 10:34
So, I would like to obtain ...
2018-03-08 10:30
I have tried to used the dateshift function however, I haven't had a good solution
0 Comments
Accepted Answer
  Rik
      
      
 on 8 Mar 2018
        
      Edited: Rik
      
      
 on 8 Mar 2018
  
      Dateshift would be a good solution, but it can only shift to quarter years, not quarter hours. The code below is a way around this.
t1 = datetime('now','Format','yyyy-MM-dd HH:mm')
t1.Minute = 15 * floor(t1.Minute/15)
%original code:
% t1 = datetime('now','Format','yyyy-MM-dd HH:mm');
% %syntax: t = datetime(Y,M,D,H,MI,S);
% t1=datetime(year(t1),month(t1),day(t1),hour(t1),15*floor(minute(t1)/15),0);
4 Comments
  Jim McIntyre
 on 28 Apr 2020
				This answer works for the example given, but is incomplete for real times that might also have non-zero values for seconds. The answer rounds the minutes, but leaves the seconds unrounded. 
To fully round to minutes, you need to add:
t1.Second = 0
More Answers (2)
  Steven Lord
    
      
 on 8 Mar 2018
        Let's start off with the current date and time.
N = datetime('now')
Figure out the start of the hour containing N.
H = dateshift(N, 'start', 'hour')
Generate a datetime vector spaced a quarter of an hour apart, starting with H.
Q = hours(0.25)
P = H + Q*(0:4)
previousQuarterHour = P(discretize(N, P))
previousQuarterHour = interp1(P, P, N, 'previous')
If you're using release R2014b or R2015a you'll need to use find to find the last element of P that is less than or equal to N.
previousQuarterHour = P(find(P <= N, 1, 'last'))
  Jose Valles
 on 8 Mar 2018
        
      Edited: Jose Valles
 on 8 Mar 2018
  
      
      3 Comments
  Rik
      
      
 on 8 Mar 2018
				t1 = datetime('now','Format','yyyy-MM-dd HH:mm')
t1.Minute = 60 * floor((t1.Minute-15)/60)+15
This will round to the previous ##:15
See Also
Categories
				Find more on Dates and Time in Help Center and File Exchange
			
	Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!