4

I have a failing test that I've narrowed down to the DateFormatTest.d31 case below.

The test results are:

TEST NAME           OUTCOME  MESSAGE                                                                             RUNTIME (MS)
──────────────────  ───────  ──────────────────────────────────────────────────────────────────────────────────  ────────────
DateFormatTest.d1   Pass                                                                                         28          
DateFormatTest.d30  Pass                                                                                         3           
DateFormatTest.d31  Fail     System.AssertException: Assertion Failed: Expected: 2023-12-31, Actual: 2024-12-31  
                             (System Code)                                                                       
                             Class.acl.DateFormatTest.d31: line 11, column 1  

Before adding extra test cases I though this might be timezone related but note that the formatted date of 2024-12-31 is 1 year ahead of the expected date of 2023-12-31 not 1 day ahead.

@IsTest
private class DateFormatTest {

    @IsTest
    static void d30() {
        Assert.areEqual('2023-12-30', format(Date.newInstance(2023, 12, 30)));
    }

    @IsTest
    static void d31() {
        Assert.areEqual('2023-12-31', format(Date.newInstance(2023, 12, 31)));
    }

    @IsTest
    static void d1() {
        Assert.areEqual('2024-01-01', format(Date.newInstance(2024, 1, 1)));
    }

    private static String format(Date d) {
        DateTime dt = DateTime.newInstanceGmt(d.year(), d.month(), d.day());
        return dt.formatGmt('YYYY-MM-dd');
    }
}

No permutation of with/without Gmt helps. What am I missing here? Or if you have a way to do this formatting without hitting this problem please post it.

I'll resort to doing the format myself for now to avoid this and will report it to SF if it's just not me missing something obvious.

1 Answer 1

4

Duh NO.

Some more Googling reveals this answer from a different language:

Difference between 'YYYY' and 'yyyy' in NSDateFormatter

that can be summarized as:

use yyyy not YYYY

and that fixes the problem.

Worth checking for YYYY in your code as most test cases will pass with that (wrong) value per this link:

It uses yyyy to specify the year component. A common mistake is to use YYYY. yyyy specifies the calendar year whereas YYYY specifies the year (of “Week of Year”), used in the ISO year-week calendar. In most cases, yyyy and YYYY yield the same number, however they may be different. Typically you should use the calendar year.

You must log in to answer this question.

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