如何使日期更漂亮?

时间:2021-01-13 16:03:58

标签: javascript reactjs date

我想让我的约会对象更漂亮

看起来是这样的: 2021-11-01T00:00:00.000Z

我想做dd/mm/yy

还有我的代码:

<tr>
            <td type="text" id="montant" name="montant">
              {" "}
              {element.montant / 100}€
            </td>
            <td type="date" id="date" name="date">
              {" "}
              {element.date}
            </td>
</tr>

3 个答案:

答案 0 :(得分:1)

您可以使用外部库,例如 D3、moment.js 或 date-fns。

如果实在不想使用任何外部库,可以试试下面的代码:

Date.prototype.format = function(fmt) { 
     var o = { 
        "M+" : this.getMonth()+1,                
        "d+" : this.getDate(),          
        "h+" : this.getHours(),            
        "m+" : this.getMinutes(),          
        "s+" : this.getSeconds(),                
        "q+" : Math.floor((this.getMonth()+3)/3), 
        "S"  : this.getMilliseconds()          
    }; 
    if(/(y+)/.test(fmt)) {
            fmt=fmt.replace(RegExp.$1, (this.getFullYear()+"").substr(4 - RegExp.$1.length)); 
    }
     for(var k in o) {
        if(new RegExp("("+ k +")").test(fmt)){
             fmt = fmt.replace(RegExp.$1, (RegExp.$1.length==1) ? (o[k]) : (("00"+ o[k]).substr((""+ o[k]).length)));
         }
     }
    return fmt; 
}
// Then you can format the date object by:
console.log(new Date().format("yy/MM/dd")) // return: 21/01/14

答案 1 :(得分:0)

你可以试试这个

<tr>
            <td type="text" id="montant" name="montant">
              {" "}
              {element.montant / 100}€
            </td>
            <td type="date" id="date" name="date">
              {" "}
              {new Date(element.date).toLocaleDateString()}
            </td>
</tr>

答案 2 :(得分:0)

我推荐moment.js书店。有了它,您可以轻松地进行日期格式化。 例如:const myFormatDate = moment (myDate) .format ('DD / MM / YYYY')

https://momentjs.com/docs/#/parsing/string-format/