最近项目使用到很多关于时间的处理操作,趁此整理一份关于时间所常用到的方法,以便日后查看。
创建Date对象
let date=new Date() //可以添加参数,形式为字符串或时间戳
date.getFullYear()//获取当前年
date.getMonth() //获取当前月(注意使用时,获取值是从0开始,需要+1)
date.getDate() //获取当前日期
date.getDay() //获取星期几(0-6)
date.getHours() //获取当前小时
date.getMinutes() //获取当前分钟数
date.getSeconds() //获取当前秒数
date.getMilliseconds() //获取当前毫秒数
date.getTime() //获取1970.1.1至今的毫秒数(ms)
//以下是获取指定时间
date.setFullYear(2023) //指定年为2023年
date.setMonth(1) //指定月为2月(0-11)
date.setDate(1) //指定日为1号(1-31)
date.setHours(0) //指定小时(0-23)
date.setMinutes() //指定分钟 (0-59)
date.setSeconds() //指定分钟 (0-59)
//以下是日期转换
toString() //将日期转换成字符串
toISOString() //使用ISO标准将 Date 对象转换为字符串 格式为: YYYY-MM-DDTHH:mm:ss.sssZ
toDateString() //将Date 对象的日期部分转换为字符串。
toTimeString() //将 Date 对象的时间部分转换为字符串。
toUTCString() //根据世界时间,将 Date 对象转换为字符串。
toLocalDateString() //根据北京时间,将Date 对象的日期部分转换为字符串。
toLocalTimeString() //根据北京时间,将 Date 对象的时间部分转换为字符串。
//常用数据
1.获取当月第一天和最后一天
2.获取指定日期的第一天和最后一天
3.获取开始时间和结束时间的时间间隔天数
目前更新到这里,后续有更多时间操作会继续更新,觉得有帮助到您,麻烦点点赞