JS将时间戳转换为日期时间格式
2018-01-24 10:04
585 查看
最近项目需要在前端将一个13位的时间戳显示成日期格式,在网上查了很多都不符合要求,只有一个是能满足要求的,在这记录一下,说不定以后还用的着。
13位时间戳改为yyyy-MM-dd HH-mm-ss 格式
目标时间戳:1516324500000
结果如下:
13位时间戳改为yyyy-MM-dd HH-mm-ss 格式
目标时间戳:1516324500000
//将时间戳改为yyyy-MM-dd HH-mm-ss function formatDateTime(unix) { var now = new Date(parseInt(unix) * 1); now = now.toLocaleString().replace(/年|月/g, "-").replace(/日/g, " "); if(now.indexOf("下午") > 0) { if (now.length == 18) { var temp1 = now.substring(0, now.indexOf("下午")); //2014/7/6 var temp2 = now.substring(now.indexOf("下午") + 2, now.length); // 5:17:43 var temp3 = temp2.substring(0, 1); // 5 var temp4 = parseInt(temp3); // 5 temp4 = 12 + temp4; // 17 var temp5 = temp4 + temp2.substring(1, temp2.length); // 17:17:43 now = temp1 + temp5; // 2014/7/6 17:17:43 now = now.replace("/", "-"); // 2014-7/6 17:17:43 now = now.replace("/", "-"); // 2014-7-6 17:17:43 }else { var temp1 = now.substring(0, now.indexOf("下午")); //2014/7/6 var temp2 = now.substring(now.indexOf("下午") + 2, now.length); // 5:17:43 var temp3 = temp2.substring(0, 2); // 5 if (temp3 == 12){ temp3 -= 12; } var temp4 = parseInt(temp3); // 5 temp4 = 12 + temp4; // 17 var temp5 = temp4 + temp2.substring(2, temp2.length); // 17:17:43 now = temp1 + temp5; // 2014/7/6 17:17:43 now = now.replace("/", "-"); // 2014-7/6 17:17:43 now = now.replace("/", "-"); // 2014-7-6 17:17:43 } }else { var temp1 = now.substring(0,now.indexOf("上午")); //2014/7/6 var temp2 = now.substring(now.indexOf("上午")+2,now.length); // 5:17:43 var temp3 = temp2.substring(0,1); // 5 var index = 1; var temp4 = parseInt(temp3); // 5 if(temp4 == 0 ) { // 00 temp4 = "0"+temp4; }else if(temp4 == 1) { // 10 11 12 index = 2; var tempIndex = temp2.substring(1,2); if(tempIndex != ":") { temp4 = temp4 + "" + tempIndex; }else { // 01 temp4 = "0"+temp4; } }else { // 02 03 ... 09 temp4 = "0"+temp4; } var temp5 = temp4 + temp2.substring(index,temp2.length); // 07:17:43 now = temp1 + temp5; // 2014/7/6 07:17:43 now = now.replace("/","-"); // 2014-7/6 07:17:43 now = now.replace("/","-"); // 2014-7-6 07:17:43 } return now; }; alert(formatDateTime(1516324500000));
结果如下:
相关文章推荐
- 工具类_js移动端时间戳转日期格式-将一个时间转换成x小时前、y天前
- js 时间戳 与 字符串 和 日期格式 的转换
- js时间戳与日期格式之间的转换
- js时间戳转换日期格式和日期计算
- js获取当前时间,并将标准日期格式转换成Long型
- js时间戳与日期格式之间的转换
- js时间戳与日期格式之间的相互转换
- js把时间戳转换为日期格式
- 把时间戳转换为日期格式的js代码
- js时间戳和日期格式的转换
- 在JS中如何把毫秒转换成规定的日期时间格式实例
- js中Date日期格式转换以及时间和毫秒之间的转换
- JS将时间戳转换成日期格式
- js转换时间戳成日期格式
- js将日期格式的时候转换成时间搓
- JS日期格式字符串转换为日期毫秒数和时间毫秒数转换为日期
- js 时间戳日期转换为指定格式
- 用js将从后台得到的时间戳(毫秒数)转换为想要的日期格式
- js时间戳转换为日期格式
- js将日期格式的时候转换成时间搓