时间戳转换js

一、时间转换时间戳

var date = new Date(); //时间对象
var str = date.getTime(); //转换成时间戳

注:

在安卓手机中得到的常量validDateTime的值正确,在苹果手机中得到的返回值为Invalid Date,测试后发现,当日期格式为:‘2022:08:16 12:00:00’和‘2022-08-16 12:00:00’时,返回的数据都为Invalid Date 只有年月日之间的连接符为'/'时,返回的才是正确的数值。处理方法如下:

var time = '2022-08-16 12:00:00';
var strtime = time.replace(/-/g, '/')
var date = new Date(strtime);

二、时间戳转换为时间

1.转换成形 ‎2022年‎18月‎16‎日‎ ‎17:‎00‎:‎00 格式:

var item = new Date(1659424247000).toLocaleString();

2.还可以这样

// 有三种方式获取,在后面会讲到三种方式的区别 time1 = date.getTime(); time2 = date.valueOf(); time3 = Date.parse(date); /* 三种获取的区别: 第一、第二种:会精确到毫秒 第三种:只能精确到秒,毫秒将用0来代替 比如上面代码输出的结果(一眼就能看出区别): 1398250549123 1398250549123 1398250549000 */

3. 转换成更多其他的格式:

// 简单的一句代码
var date = new Date(时间戳); //获取一个时间对象

date.getFullYear();  // 获取完整的年份(4位,1970)
date.getMonth();  // 获取月份(0-11,0代表1月,用的时候记得加上1)
date.getDate();  // 获取日(1-31)
date.getTime();  // 获取时间(从1970.1.1开始的毫秒数)
date.getHours();  // 获取小时数(0-23)
date.getMinutes();  // 获取分钟数(0-59)
date.getSeconds();  // 获取秒数(0-59)

例子

// 比如需要这样的格式 yyyy-MM-dd hh:mm:ss
var date = new Date(1659424247000);
Y = date.getFullYear() + '-';
M = (date.getMonth()+1 < 10 ? '0'+(date.getMonth()+1) : date.getMonth()+1) + '-';
D = date.getDate() + ' ';
h = date.getHours() + ':';
m = date.getMinutes() + ':';
s = date.getSeconds(); 
console.log(Y+M+D+h+m+s); 
// 输出结果:2014-04-23 18:55:49

猜你喜欢

转载自blog.csdn.net/L_15737525552/article/details/126370583
今日推荐