0

How to convert ISOString to local ISOString in javascript?

I have ISO 8086 style string(e.g. '2013-02-18T16:39:17+00:00')

And I want to convert that to local ISO_8601 style string...

'2013-02-18T16:39:17+00:00' -> '2013-02-19T01:39:17+09:00'

What should I do?

chobo
  • 4,830
  • 5
  • 23
  • 36

1 Answers1

1

There only is a .toISOString() method, but that will not use the local timezone. For that, you will need to format the string yourself:

function toLocaleISOString(date) {
    function pad(n) { return ("0"+n).substr(-2); }

    var day = [date.getFullYear(), pad(date.getMonth()+1), pad(date.getDate())].join("-"),
        time = [date.getHours(), date.getMinutes(), date.getSeconds()].map(pad).join(":");
    if (date.getMilliseconds())
        time += "."+date.getMilliseconds();
    var o = date.getTimezoneOffset(),
        h = Math.floor(Math.abs(o)/60),
        m = Math.abs(o) % 60,
        o = o==0 ? "Z" : (o<0 ? "+" : "-") + pad(h) + ":" + pad(m);
    return day+"T"+time+o;
}
Bergi
  • 630,263
  • 148
  • 957
  • 1,375