今天学习了时间搓的利用,来简单做个笔记。
通过JS内置对象Date
JavaScript具有一个内置 Date 对象,该对象存储日期和时间并提供相应的处理日期和时间的方法
年月日的获取
先 获得时间搓 const date = new Date()
年月日的转换
const currentYear = date.getFullYear(); //当前年
const today = date.getDate(); //当前日
const currentMonth = date.getMonth() + 1; //当前月
var dt = new Date();
var HH = dt.getHours(); //小时
var mm = dt.getMinutes();//分钟
var ss = dt.getSeconds();//秒数
给了我们一个时间,计算出他距离我们现在的天数时数分数秒数。
首先总毫秒数是基于1970年1月1日(世界标准时间)起的毫秒数
//获取当前时间总毫秒数
let nowDate = + new Date();
//获取2022-10-1 08:00:00的总毫秒数
let newDate = + new Date("2022-10-1 08:00:00");
这样先算出来2个时间段的总毫秒数,相减就得到2个时间段的时间差
let times = (newDate - nowDate) / 1000; //总秒数
再利用公式算出天,小时,分钟,秒数
// 天: d = parseInt(总秒数 / 60 / 60 /24)
// 小时: h = parseInt(总秒数 / 60 / 60 % 24)
// 分钟: m = parseInt(总秒数 / 60 % 60 )
// 秒数: s = parseInt(总秒数 % 60)
是不是简单粗暴>.<!