当前位置:网站首页>js中的Date对象 及 将时间戳转换为yy-mm-dd hh:mm:ss格式的方法
js中的Date对象 及 将时间戳转换为yy-mm-dd hh:mm:ss格式的方法
2022-08-09 15:03:00 【不知-_】
Date
Date 对象用于处理日期和时间。
创建
日期对象是用 new Date()
创建的。
有 4 种方法创建新的日期对象:
方法 | 说明 |
---|---|
new Date() | 用当前日期和时间创建新的日期对象 |
new Date(year, month, day, hours, minutes, seconds, milliseconds) | 用指定日期和时间创建新的日期对象。 参数可以是7~2个,分别为年、月、日…但不能只有1个参数,如果只提供一个参数,则将其视为毫秒。 |
new Date(milliseconds) | 创建一个零时加毫秒的新日期对象 |
new Date(date string) | 从日期字符串创建一个新的日期对象 |
说明:
- JavaScript 从 0 到 11 计算月份。一月是 0。十二月是11。
- 一位和两位数年份将被解释为 19xx 年。
- JavaScript 将日期存储为自 1970 年 1 月 1 日 00:00:00 UTC(协调世界时)以来的毫秒数。
零时间是 1970 年 1 月 1 日 00:00:00 UTC。
JavaScript(默认情况下)将以全文本字符串格式输出日期:
Wed Mar 25 2015 08:00:00 GMT+0800 (中国标准时间)
在 HTML 中显示日期对象时,会使用 toString() 方法自动转换为字符串。
<script>
let d1 = new Date();
console.log('d1: ',d1);
let d2 = new Date(2020, 7, 14, 15, 37, 30);
console.log('d2: ',d2); //注意创建出来的日期月份为8月
let d3 = new Date(98, 12, 6);
console.log('d3: ',d3); //Wed Jan 06 1999 00:00:00 GMT+0800 (中国标准时间)
let d4 = new Date("October 13, 2014 11:13:00");
console.log('d4: ',d4)
let d5 = new Date(100000000000)
console.log('d5: ',d5)
let d6 = new Date(-100000000000) //1970 年 1 月 1 日减去 100 000 000 000 毫秒大约是 1966 年 10 月 31 日
console.log('d6: ',d6)
</script>
注意:
使用构造函数( new Date()
)创建是对象类型
使用Date()
函数创建是字符串类型
<script>
let d1 = new Date();
console.log(d1);
console.log(typeof d1);
let d2 = Date();
console.log(d2);
console.log(typeof d2);
</script>
Date对象的方法
get时间
set时间
转字符串
将时间戳转换为yy-mm-dd hh:mm:ss格式的方法
<script>
function getFullTime(timestamp){
let date = new Date(timestamp); //时间戳为10位需*1000,时间戳为13位的话不需乘1000
let Y = date.getFullYear() + '-';
let M = ((date.getMonth() + 1) < 10 ? '0' + (date.getMonth() + 1) : (date.getMonth() + 1)) + '-';
let D = (date.getDate() < 10 ? '0' + date.getDate() : date.getDate()) + ' ';
let h = (date.getHours() < 10 ? '0' + date.getHours() : date.getHours()) + ':';
let m = (date.getMinutes() < 10 ? '0' + date.getMinutes() : date.getMinutes()) + ':';
let s = date.getSeconds() < 10 ? '0' + date.getMinutes() : date.getMinutes()
return Y + M + D + h + m + s;
}
let time = getFullTime(1627085595000);
console.log(time); //2021-07-24 08:13:13
</script>
边栏推荐
猜你喜欢
godot正确设置2d像素游戏
基于FTP协议的文件上传与下载
Basic Concepts of Software Security
Word 2016 撰写论文(1): 公式居中、编号右对齐
Vim practical skills_3. Visual mode and command mode
weiteUP-ciscn_2019_c_1
ping www.baidu.com虚拟机中ping百度
Heap series _0x04: Internal structure of heap (_HEAP=_HEAP_SEGMENT+_HEAP_ENTRY)
Excel绘制统计图
Monte Carlo simulation
随机推荐
Heap series _0x02: The past and present of the heap (WinDbg+Visual Studio compilation)
vs2017下配置sqlite3环境
详解VLAN与划分广播域
unity中AO、metallic、roughness贴图的使用方式
Uart串口学习
fiddler工具栏及其使用
标准IO及其各函数用法
DOS命令
Time series analysis
客户端媒体引擎框架
Unity Shader零基础入门1:纯色物体
FPGA--基础语句、计数器、测试仿真语句(个人学习记录2022.7.20)
Introduction to common commands in SQLMap
unity shader 入门 全透明与半透明效果实现
RAID磁盘阵列详解
GO 使用 Protobuf实用指南
Mysql(四)
Unity Shader零基础入门2:环境光、漫反射、高光
指针常量和常量指针和类中的const
QT程序设计多人聊天室(基于QT、sqlite3、TCP/IP)