How do I output an ISO 8601 formatted string in JavaScript?

后端 未结 14 1521
小鲜肉
小鲜肉 2020-11-22 08:41

I have a Date object. How do I render the title portion of the following snippet?



        
14条回答
  •  臣服心动
    2020-11-22 09:12

    Almost every to-ISO method on the web drops the timezone information by applying a convert to "Z"ulu time (UTC) before outputting the string. Browser's native .toISOString() also drops timezone information.

    This discards valuable information, as the server, or recipient, can always convert a full ISO date to Zulu time or whichever timezone it requires, while still getting the timezone information of the sender.

    The best solution I've come across is to use the Moment.js javascript library and use the following code:

    To get the current ISO time with timezone information and milliseconds

    now = moment().format("YYYY-MM-DDTHH:mm:ss.SSSZZ")
    // "2013-03-08T20:11:11.234+0100"
    
    now = moment().utc().format("YYYY-MM-DDTHH:mm:ss.SSSZZ")
    // "2013-03-08T19:11:11.234+0000"
    
    now = moment().utc().format("YYYY-MM-DDTHH:mm:ss") + "Z"
    // "2013-03-08T19:11:11Z" <- better use the native .toISOString() 
    

    To get the ISO time of a native JavaScript Date object with timezone information but without milliseconds

    var current_time = Date.now();
    moment(current_time).format("YYYY-MM-DDTHH:mm:ssZZ")
    

    This can be combined with Date.js to get functions like Date.today() whose result can then be passed to moment.

    A date string formatted like this is JSON compilant, and lends itself well to get stored into a database. Python and C# seem to like it.

提交回复
热议问题