Apex - Subtract minutes from DateTime Object

Mohamed Farag picture Mohamed Farag · Jan 11, 2014 · Viewed 10k times · Source

I'd like to subtract 5 minutes from DateTime.now() May I know how I can do this?

Thanks!

Answer

eyescream picture eyescream · Jan 11, 2014

addMinutes()

It has add in it's name but nobody says you can't pass a negative number.

DateTime dt = System.now();
DateTime earlier = dt.addMinutes(-5);
DateTime fullHour = dt.addMinutes( -dt.minute() ).addSeconds( -dt.second() );

System.debug(dt + '\t' + earlier + '\t' + fullHour);

2014-01-11 08:40:13     2014-01-11 08:35:13     2014-01-11 08:00:00