5

I was having issues with a method that was repeatedly printing out wrong dates, when I executed this in anonymous apex

Date foo = date.newinstance(2016, 27, 7);//year, month, day
system.debug(foo);

This is what was output:

19:02:05:002 USER_DEBUG [2]|DEBUG|2018-03-07 00:00:00

Has anyone else encountered this or know of a work around?

8
  • 1
    What were you expecting it to do?
    – sfdcfox
    Apr 6 '17 at 23:10
  • 2
    there is no month 27 so it adds the remaining months to it i believe
    – Eric
    Apr 6 '17 at 23:10
  • 1
    No problem. Not sure about the adding of months but I think thats what it is doing. 27-4 = 23, add 23 months get 3-2018
    – Eric
    Apr 6 '17 at 23:12
  • 2
    @Eric JavaScript does the same thing. I think it's to make it easier to find arbitrary dates (like you could add 60 months to find the end date).
    – sfdcfox
    Apr 6 '17 at 23:16
  • 1
    @Eric Yeah, the year sets the date to Jan 1, XXXX (whatever), then the second param calls addMonths, and the third param calls addDays. I think. It's not documented, but it's not strictly a bug.
    – sfdcfox
    Apr 6 '17 at 23:18
14

Date.newInstance actually seems to behave as follows:

public class Date {
    public static Date newInstance(Integer year, Integer month, Integer day) {
        Date d = new Date(1, 1, 1);
        d.addYears(year-1);
        d.addMonths(month-1);
        d.addDays(day-1);
        return d;
    }
}

Curiously, year cannot be negative, so it has the net effect of wrapping upwards:

Date.newInstance(-3, 1, 1);
// 0004-01-01

The system represents the date as a number of milliseconds, so if you exceed the maximum value, your Date will debug oddly:

Date.newInstance(1000000000, 1, 1);
// 169104628-12-10 19:08:16

This allows you to do things like...

Last Day of Previous Year

Date.newInstance(year, 1, 0);

Last Day of Previous Month

Date.newInstance(year, month, 0);

Determine End Date of 60-Month Contract:

Date.newInstance(startYear, startMonth+60, 0);
1
  • lol - Jynx - much better than mine
    – Eric
    Apr 6 '17 at 23:33

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.