js string to datetime add 2 hours

I'm working with a PHP Api witch gives me this json:

"title": "hemen",
"category": "time",
"start": "2021-09-27T09:22:00+00:00",
"end": "2021-09-27T13:22:00+00:00",
"isAllDay": false,
"calendar": [{"id": 1}],
"body": null

The problem is that in my frontend (Vue) I'm convering the start and end dates to datetime but it adds 2 hours and I don't know why or the best option to fix it.

axios.get('/api/schedules.json').then(function (response) {
    let dataOri = response.data;
    // convert
    dataOri.forEach(element => {
        element.start = moment(element.start, "YYYY-MM-DDTHH:mm:ssZ").format("YYYY-MM-DD HH:mm:ss");
        console.log(element.start); // prints '2021-09-27 11:22:00' instead of '2021-09-27 09:22:00'

        element.end = moment(element.end, "YYYY-MM-DDTHH:mm:ssZ").format("YYYY-MM-DD HH:mm:ss");
        console.log(element.end); // prints '2021-09-27 15:22:00' instead of '2021-09-27 13:22:00'
    self.filterSchedules = dataOri;

1 answer

  • answered 2021-09-27 11:33 Tatranskymedved

    You are parsing the time with information that "original time is within specified timezone" (+00:00) and then printing it in local time.

    There are 2 approaches how to handle the situation, you can either:

    • Ignore these timezones completely (bad approach)
    • Include/parse this timezone information and output it in original UTC time (good approach)

    var dateAsStr = "2021-09-27T09:22:00+00:00";
    var resultWrong = moment(dateAsStr, "YYYY-MM-DDTHH:mm:ssZ").format("YYYY-MM-DD HH:mm:ss");
    var resultBadApproach = moment(dateAsStr, "YYYY-MM-DDTHH:mm:ss").format("YYYY-MM-DD HH:mm:ss");
    var resultGoodAproach = moment(dateAsStr, "YYYY-MM-DDTHH:mm:ssZ").utc().format("YYYY-MM-DD HH:mm:ss");
    console.log("wrong: " + resultWrong);
    console.log("correct (bad approach): " + resultBadApproach);
    console.log("correct (good approach): " + resultGoodAproach);
    <script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.29.1/moment.min.js"></script>

How many English words
do you know?
Test your English vocabulary size, and measure
how many words do you know
Online Test
Powered by Examplum