当前位置: 首页 > web>阅读正文

js通用日期格式化

2022.5.21 朱丰华 1575 次 留下评论 508字

推荐格式化为中文的年月日,例如:

2022年5月18日 下午3:00

代码实现如下:

<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8"/>
        <title>示例</title>
    </head>
    <body>
      <script>
    Date.prototype.auto = function(){
        let year = this.getFullYear();
        let mon = this.getMonth()+1;
        let day = this.getDate();
        let hours = this.getHours();
        let apm = "";
        if(hours > 12){
            apm = "下午";
            hours -= 12;
        }else{
            apm = "上午";
        }
        let min = this.getMinutes();
        if(this.getMinutes()>0){
            min = this.getMinutes();
        }else{
            min = "00";
        }
        return `${year}年${mon}月${day}日 ${apm}${hours}:${min}`
    }
    document.write(new Date().auto());
      </script>
    </body>
</html>

本篇完,还有疑问?留下评论吧

发表评论

您的电子邮箱地址不会被公开。 必填项已用*标注