Js_react 时间戳和格式之间转换
Js中的date:
JS获取时间戳:(都是毫秒级时间戳,换成秒时间戳需要/1000)
var timestamp1 = Date.parse(new Date());//只能精确到秒,后面的毫秒用000代替 var timestamp2 = (new Date()).valueOf(); var timestamp3 = new Date().getTime();
将时间戳转换为日期格式:如果是秒级时间戳,需要乘以1000
function timestampToTime(timestamp) { var date = new Date(timestamp * 1000);//时间戳为10位需*1000,时间戳为13位的话不需乘1000 var Y = date.getFullYear() + '-'; var M = (date.getMonth()+1 < 10 ? '0'+(date.getMonth()+1) : date.getMonth()+1) + '-'; var D = date.getDate() + ' '; var h = date.getHours() + ':'; var m = date.getMinutes() + ':'; var s = date.getSeconds(); return Y+M+D+h+m+s; }
function getLocalTime(timestamp) { return new Date(parseInt(timestamp) * 1000).toLocaleString().replace(/:\d{1,2}$/,' '); }
function getLocalTime(timestamp) { return new Date(parseInt(timestamp) * 1000).toLocaleString().substr(0,17)}
但我们现在好像都用moment对象:
const timestamp = moment(new Date()).valueOf(); const formattime = moment(timestamp).format('YYYY-MM-DD HH:mm:ss');
具体moment的其他用法
请参考:
https://www.jianshu.com/p/9c10543420de
本文来自博客园,作者:LeeJuly,转载请注明原文链接:https://www.cnblogs.com/peterleee/p/10779198.html