How can I convert datetime microformat to local time in javascript?

前端 未结 2 1553
余生分开走
余生分开走 2021-01-16 15:54

I have a page that is currently using the datetime microformat to display a timestamp, but I have only been showing the human-readable time for my own time zone:

<         


        
2条回答
  •  栀梦
    栀梦 (楼主)
    2021-01-16 16:24

    EcmaScript formalized the addition of an ISO-8601 style string as an imput for a JavaScript date. Since most JS implementations don't support this, I created a wrapper to the Date object, that has this functionality. If you set the title tags to output in UTC/GMT/Z/Zulu offset, you can use my EcmaScript 5 extensions for JS's Date object.

    For DateTime values that are to be used in client-side scripts, I generally try to always do the following. Store date+time in UTC zone (even in databases). Transmit date-times in UTC zone. From client to server, you can use the .toISOString() method in the above link. From server-to client this is relatively easy.

    Via jQuery (with extension):

    $('.published').each(function(){
      var dtm = new Date(this.title);
      if (!isNaN(dtm)) {
        this.text(dtm.toString());
      }
    });

    I don't recall if I added support for non-utc date-times in the input, but wouldn't be too hard to account for them.

提交回复
热议问题