1

I want to get a time string in

"%Y%m-%dT%H:%M:%S%z"

format in chrome using JavaScript. But chrome just returns 'Z' character like below.

new Date().toISOString()
->"2015-07-23T07:41:36.617Z"

Although I know an upper result is valid, my project also includes a c++ application. So I want to unify date format like below.

2015-07-23T16:41:36.617+09:00

So are there any good ways to realize my date format?

ES6 specification

http://www.ecma-international.org/ecma-262/6.0/#sec-date-time-string-format

jef
  • 3,890
  • 10
  • 42
  • 76
  • [How to ISO 8601 format a Date with Timezone Offset in JavaScript?](https://stackoverflow.com/a/17415677/7598333) – Asalan Feb 28 '18 at 23:13

2 Answers2

1

So are there any good ways to realize my date format?

If you want an ISO-8601 version in local time with offset, all you can do is use the non-UTC versions of getDay, getMonth, etc., get the timezone offset from getTimezoneOffset, and build the string yourself. (Or use a library like MomentJS.) There's nothing in the spec that will do it.

T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
0

If there’s a good way depends. Fact is, there is no built-in method for that. But you can build one on your own by using Date.getTimezoneOffset() and doing some modulus. Here’s a lead:

// set up date 2009-02-13T23:31:30.123Z (equivalent to 1234567890123 milliseconds):
var localDate = new Date(1234567890123);
// get local time offset, like -120 minutes for CEST (UTC+02:00):
var offsetUTC = new Date().getTimezoneOffset();
// set date to local time:
localDate.setMinutes(localDate.getMinutes() - offsetUTC);
offsetUTC = {
    // positive sign unless offset is at least -00:30 minutes:
    "s": offsetUTC < 30 ? '+' : '-',
    // local time offset in unsigned hours:
    "h": Math.floor(Math.abs(offsetUTC) / 60),
    // local time offset minutes in unsigned integers:
    "m": ~~Math.abs(offsetUTC) % 60
};
offsetUTC = offsetUTC.s + // explicit offset sign
            // unsigned hours in HH, dividing colon:
            ('0'+Math.abs(offsetUTC.h)+':').slice(-3) +
            // minutes are represented as either 00 or 30:
            ('0'+(offsetUTC.m < 30 ? 0 : 30)).slice(-2);

localDate = localDate.toISOString().replace('Z',offsetUTC);
// === "2009-02-13T23:31:30.123+02:00" (if your timezone is CEST)
     

Or a little less verbose:

localDate = localDate.toISOString().replace('Z',(offsetUTC<30?'+':'-')+
            ('0'+Math.floor(Math.abs(offsetUTC)/60)+':').slice(-3)+
            ('0'+((~~Math.abs(offsetUTC)%60)<30?0:30)).slice(-2));

Note that…

dakab
  • 5,379
  • 9
  • 43
  • 67