I have been experiencing a strange issue since Dec 27. When I try to format a date to a string, it is giving me next year date. When I executed this in Workbench, I find that the formatGmt() method of Datetime class is actually giving me next year’s date.

So, in results, I am getting the date as 2015-12-29T11:59:12.988Z but the corresponding string date (using YYYYMMdd) format is 20161229.

enter image description here

This was working fine till Dec 27 and there has been no change to the underlying code.

I read the specs of the formatGmt method again – am I missing something obvious here?


Use small y instead of capital Y. This will give you correct output.

Datetime myDatetime = Datetime.now();
String myDatetimeStr = myDatetime.format('dd/MM/yyyy');

IF you looked into this link


The capital Y merge field is the WEEK YEAR - which from the 27th December 2015 is IN 2016!

The lower case y merge field is the CALENDAR YEAR - which will be 2015 as expected.

  • ahh. you nicked my magic answer ;) this question comes up 10 times every year at the end of the year. – Simon Lawrence Dec 29 '15 at 12:37
  • 1
    @SimonLawrence Yes credit goes to you. Thank you for finding out... – Ratan Paul Dec 29 '15 at 12:38

please use year string in small case like Datetime.now().formatGMT('yyyy/MM/dd'). there is a difference between 'dd/MM/YYYY' and 'dd/MM/yyyy'. you can refer this link to understand in better way Date and Time Patterns

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.