0

I have the following code for new Date() along with a function that formats the new Date() to something a bit more digestible:

data.onbCase.push({
                    first_name: onbCase.getDisplayValue('subject_person.first_name'),
                    last_name: onbCase.getDisplayValue('subject_person.last_name'),
                    start_date: formatDate(new Date(onbCase.getDisplayValue('hr_profile.employment_start_date')))   
                });

function formatDate(date) {

    var monthNames = [
        "January", "February", "March",
        "April", "May", "June", "July",
        "August", "September", "October",
        "November", "December"
    ];

    var day = date.getDate(), 
            monthIndex = date.getMonth(),
            year = date.getFullYear();

    return new Date(monthNames[monthIndex].substr(0,3) + ' ' + day + ', ' + year);
}

      <td ng-show="c.options.start_date" title="{{item.start_date}}">{{item.start_date | date:'mediumDate'}}</td>

However, this always returns a date that is one day behind the correct date. Can someone explain why this happens and how to fix it? I know I can simply add 1 to the getDate():

var day = date.getDate() +1;

This seems incorrect though...any advice?

Dave
  • 1,257
  • 2
  • 27
  • 58

1 Answers1

1

For more information see this question: Is the Javascript date object always one day off?

The new Date() string parser is not reliable, because you get different results for different string date formats.

new Date()
// Fri Feb 15 2019 15:08:14 GMT-0600 (Central Standard Time)

new Date("2019-02-15")
// Thu Feb 14 2019 18:00:00 GMT-0600 (Central Standard Time)

new Date("2019-02-15 00:00:00")
// Thu Feb 15 2019 18:00:00 GMT-0600 (Central Standard Time)

new Date("02/15/2019")
// Fri Feb 15 2019 00:00:00 GMT-0600 (Central Standard Time)

Some date formats, especially if you don't include time information, will treat your date as originating in Greenwich Mean Time and then offset your date by your computer's locale. This will result in the date being offset by negative 6 hours(CST) effectively altering your day to the day before.

Pop-A-Stash
  • 6,572
  • 5
  • 28
  • 54