3

How should i compare two datetime in apex class ? After comparison i need to sort this datetime in ascending order.

Datetime firstDate = datetime.valueOf(stringdate1);
Datetime secondDate = datetime.valueOf(stringdate2);

long dt1 = firstDate.getTime() / 1000;
long dt2 = secondDate.getTime() /1000;

if((dt1 - dt2) < 0){    
    sortedlist.add(authObject);
}

Is it right way to compare the date and time.

1
  • 3
    Why not just use firstDate < secondDate? Mar 6, 2014 at 13:29

2 Answers 2

9

Dates are primitives in Apex and can be compared directly:

Datetime firstDate = datetime.valueOf(stringdate1);
Datetime secondDate = datetime.valueOf(stringdate2);

if(firstDate < secondDate){    
    sortedlist.add(authObject);
}

I would be cognizant of timezones and other quirks, however.

Nitpick: I would lose the "list" in "sortedlist." Help put a stake through the heart of Hungarian notation.

0

Use sort()

Datetime firstDate = System.now();
Datetime secondDate = System.today();

List<Datetime> sorted = new List<Datetime>();

sorted.add(firstDate);
sorted.add(secondDate);

sorted.sort();

System.debug(sorted); // DEBUG|(2015-12-22 00:00:00, 2015-12-22 09:37:19)

Sort manually

Datetime firstDate = System.now();
Datetime secondDate = System.today();

List<Datetime> sorted = new List<Datetime>();

if(firstDate < secondDate){
  sorted.add(firstDate);
  sorted.add(secondDate);
} else {
  sorted.add(secondDate);
  sorted.add(firstDate);
}

System.debug(sorted); // DEBUG|(2015-12-22 00:00:00, 2015-12-22 09:37:19)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.