Javascript date format like ISO but local

前端 未结 7 1499
广开言路
广开言路 2020-12-11 00:06

how do I format a javascript date like ISO format, but in local time?

with myDate.toISOString() I am getting the time as: \"2012-09-13T19:12:23.826Z\"

7条回答
  •  情深已故
    2020-12-11 00:36

    I went with what Denis Howe said, below as a ready made function for convenience.

    Also one fix: in the original answer t-z does not work because t is a Date, not milliseconds.

    function dateToISOLikeButLocal(date) {
        const offsetMs = date.getTimezoneOffset() * 60 * 1000;
        const msLocal =  date.getTime() - offsetMs;
        const dateLocal = new Date(msLocal);
        const iso = dateLocal.toISOString();
        const isoLocal = iso.slice(0, 19);
        return isoLocal;
    }
    

    With this I get the kind of string that needed as a URL parameter:

    "2018-11-16T12:23:50"
    

提交回复
热议问题