日期

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
<!--

时间基础知识:
单位:       名称      换算
hour        小时      1day = 24hours
minute      分钟      1hour= 60minutes
second       秒        1minute = 60seconds
millisecond  毫秒(ms)     1second = 1000ms
nanoseconds  纳秒(ns)     1ms = 1000ns




1.UFC和GFT他们的区别:UFC精确到纳秒,GFT精确到毫秒,现在计算机上用的都是UFC,
   UFC和GFT格式是一致的:  Thu ,27,Aug 2021:02:20:00 GMT(但是这个GMT表示的是UFC)
   ISO 8601标注格式为:2021-09-27T08:01:44.000Z    T=分割;000Z=结束
2.UFC和GFT和ISO 8601都是从零时区开始表示 ;北京时8时区,所以需要-8小时,等于到零时区,进行换算
3.UNIX时间戳(将1970年1月1日作为起始时间开始计算,到指定时间经过的毫秒)
构造函数方法:
new Date()//得到年月日
new Date(value)//根据时间戳得到年月日
new Date('字符串')//跟随字符串返回一个日期
new Date(year,monthindex [,day[,houns[,minutes[,sconds[,milliseconds]]]]])//根据年月日时分秒毫秒,得到一个时间,月是从0开始:0=1月份
API方法:
Date.now() 得到时间戳
Date.prototype.getFullYear() //得到年
Date.prototype.getMonth() //得到月
Date.prototype.getDate() //得到日
Date.prototype.getHours()//得到小时
Date.prototype.getMinutes() //得到分钟
Date.prototype.getSeconds() //得到秒
Date.prototype.getMilliseconds() //得到毫秒
Date.prototype.toLocaleString() //更改UFC/GFT/ISO的格式语法(toUFCString(),toISOString()  )

方法:
replace('修改前的值',修改后的值),将值更换
padStart(3,'0')如果第一个值不满3位,则添加0


-->
</head>
<body>
    <script>
        //练习:将日期格式化为字符串
        //date=要格式化的日期   format格式化字符串
        function formatDate(date,format){
            var year = date.getFullYear().toString().padStart(4,'0')//年
            var getMonth = (date.getMonth()+1).toString().padStart(2,'0')//月
            var getDate = date.getDate().toString().padStart(2,'0')//日
            var getHour = date.getHours().toString().padStart(2,'0')//时
            var getMinute = date.getMinutes().toString().padStart(2,'0')//分
            var getSeconds = date.getSeconds().toString().padStart(2,'0')//秒
            var getMilliseconds = date.getMilliseconds()//毫秒
            //console.log(year,getMonth,getDate,getHour,getMinute,getSeconds,getMilliseconds)
            return format
               .replace('yyyy',year)
               .replace('MM',getMonth)
               .replace('dd',getDate)
               .replace('HH',getHour)
                .replace('mm',getMinute)
                .replace('ss',getSeconds)
                .replace('ms',getMilliseconds)
        }
        var a = new Date()
        console.log(formatDate(a,'yyyy年MM月dd日 HH时mm分ss秒ms毫秒'))
      //  formatDate(a,'yyyy年MM月dd日 HH时mm分ss秒ms毫秒')//2021年12月21日 12时13分33秒526毫秒
       
    </script>
</body>
</html>

posted on 2023-04-05 22:34  爱前端的小魏  阅读(70)  评论(0编辑  收藏  举报

导航