JavaScript html css前端 日期对象 date对象 日期格式化 时间戳

日期对象

Date对象

  • Date 对象和 Math 对象不一样,他是一个构造函数,所以我们需要实例化后才能使用

  • Date 实例用来处理日期和时间

Date()使用方法

示例:获取当前时间

复制代码
let now = new Date()
console.log(now)

示例:获取指定时间

Date() 构造函数的参数可以设置指定的时间

javascript 复制代码
let now = new Date('2000-10-10') //指定日期
console.log(now)                 //Tue Oct 10 2000 08:00:00 GMT+0800 (中国标准时间)
now = new Date('2000/10/10')     //指定日期
console.log(now)                 //Tue Oct 10 2000 08:00:00 GMT+0800 (中国标准时间)
now = new Date('2000.10.10')     //指定日期
console.log(now)                 //Tue Oct 10 2000 08:00:00 GMT+0800 (中国标准时间)


日期格式化

需要获取日期指定的部分,我们要手动得到这种格式

方法名 说明 代码
getFullYear() 获取当年 dObj.getFullYear()
getMonth() 获取当月(0-11) dObj.getMonth()
getDate 获取当天日期 dObj.getDate()
getDay 获取星期几(周日0 到 周六6) dObj.getDay()
getHours() 获取当前小时 dObj.getHours()
getMinutes() 获取当前分钟 dObj.getMinutes()
getSeconds() 获取当前秒钟 dObj.getSeconds()
setFullYear(数字) 设置日期中的年 dObj.setFullYear(2000)
setMonth(数字) 设置日期中的月(0-11) dObj.setMonth(1)
setDate(数字) 设置日期中的天 dObj.setDate(1)
setHours(数字) 设置日期中的小时 dObj.setHours(11)
setMinutes(数字) 设置日期中的分钟 dObj.setMinutes(12)
setSeconds(数字) 设置日期中的秒钟 dObj.setSeconds(13)
setTime(数字) 设置日期中的时间戳 dObj.setTime(1660449716531)

示例:

javascript 复制代码
let now = new Date('2000-10-10 11:12:13') //指定日期
let fullyear = now.getFullYear()
let month = now.getMonth() + 1
let date = now.getDate()
let day = now.getDay()
let hour = now.getHours()
let minute = now.getMinutes()
let second = now.getSeconds()
let res = `现在是${fullyear}年${month}月${date}日,${hour}点${minute}分${second}秒,星期${day}`
console.log(res) // 现在是2000年10月10日,11点12分13秒,星期2

时间戳

时间戳是指 从1970年1月1日(世界标准时间)起,到现在的毫秒数。

示例: 获取时间戳

javascript 复制代码
// 方法1. 通过 valueOf() 
let date = new Date()
console.log(date.valueOf()); // 现在距离1970.1.1 的时间戳
// 方法2. 通过 getTime()
console.log(date.getTime()); // 现在距离1970.1.1 的时间戳
// 方法3. +new Date() 简单的写法
let date1 = +new Date()
console.log(date1); // 现在距离1970.1.1 的时间戳
// 方法4. ES6 新增的 获得总的毫秒数
console.log(Date.now()); // 现在距离1970.1.1 的时间戳
相关推荐
初遇你时动了情9 分钟前
html js 原生实现web组件、web公共组件、template模版插槽
前端·javascript·html
Magnum Lehar10 分钟前
3d游戏引擎EngineTest的系统实现3
java·开发语言·游戏引擎
Mcworld85725 分钟前
java集合
java·开发语言·windows
成功人chen某26 分钟前
配置VScodePython环境Python was not found;
开发语言·python
QQ27402875629 分钟前
Soundness Gitpod 部署教程
linux·运维·服务器·前端·chrome·web3
前端小崔39 分钟前
从零开始学习three.js(18):一文详解three.js中的着色器Shader
前端·javascript·学习·3d·webgl·数据可视化·着色器
哎呦你好1 小时前
HTML 表格与div深度解析区别及常见误区
前端·html
运维@小兵1 小时前
vue配置子路由,实现点击左侧菜单,内容区域显示不同的内容
前端·javascript·vue.js
海绵宝宝贾克斯儿1 小时前
C++中如何实现一个单例模式?
开发语言·c++·单例模式
史迪仔01121 小时前
[python] Python单例模式:__new__与线程安全解析
开发语言·python·单例模式