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

后端 未结 14 1515
小鲜肉
小鲜肉 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:15

    To extend Sean's great and concise answer with some sugar and modern syntax:

    // date.js
    
    const getMonthName = (num) => {
      const months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Oct', 'Nov', 'Dec'];
      return months[num];
    };
    
    const formatDate = (d) => {
      const date = new Date(d);
      const year = date.getFullYear();
      const month = getMonthName(date.getMonth());
      const day = ('0' + date.getDate()).slice(-2);
      const hour = ('0' + date.getHours()).slice(-2);
      const minutes = ('0' + date.getMinutes()).slice(-2);
    
      return `${year} ${month} ${day}, ${hour}:${minutes}`;
    };
    
    module.exports = formatDate;
    

    Then eg.

    import formatDate = require('./date');
    
    const myDate = "2018-07-24T13:44:46.493Z"; // Actual value from wherever, eg. MongoDB date
    console.log(formatDate(myDate)); // 2018 Jul 24, 13:44
    

提交回复
热议问题