In a condition, I had to make a substraction between two datetime and check how many days a separating the two datetime like that :

if(datetime2 - datetime2 > 5){
   //do something

Of course this syntax does not work, I want to know what syntax to use for doing something like this.

1 Answer 1


you can get date part of datetime for ech date, and the compare days between two dates be means of daysBetween method. all list of methods present in Date class can be read here

Date date1 = datetime1.date();
Date date2 = datetime2.date();
if(date2.daysBetween(date1) > 5){
    //do something
  • One thing to be aware of with this approach is that the result can be off by a day (one day at most) depending on your locale and how datetime1 and datetime2 are initialized. I ran into a similar issue within the past week where DateTimet testDT = Date.Today(); System.debug(testDT.date()); would print yesterday's date in the debug log because assigning a Date to a DateTime gives the resulting time component a value of 00:00:00, and does not take locale into account. date() does take locale into account, and if you're in a UTC-x locale, midnight today - anything = yesterday
    – Derek F
    Jun 21, 2017 at 13:32
  • @DerekF how did figured out that problem? Jun 21, 2017 at 13:42
  • 1
    I'd like to say it was all due to skill and experience, but there was probably some luck involved too. I was running through my standard debugging procedure (start where the error occurs, inspect data. If data isn't what I expect it to be, go to where that data is generated/passed from. Repeat until I find the source) and noticed that DateTime.date() was giving me an unexpected value. I looked at the documentation for date() and saw it mentioned using the user's locale. I ran some simple anonymous apex to confirm my suspicion, and to confirm that dateGMT() gave me the result I wanted.
    – Derek F
    Jun 21, 2017 at 14:03

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .