js 中处理时间格式

时间格式的数据转换为时间戳

var date = new Date(); //时间对象
var str = date.getTime(); //转换成时间戳
// 简单示例
var strtime = '2014-04-23 18:55:49:123';
var date = new Date(strtime.replace(/-/g, '/'));
 
// 三种方式获取
time1 = date.getTime();
time2 = date.valueOf();
time3 = Date.parse(date);
 
/* 
三种获取的区别:
第一、第二种:会精确到毫秒
第三种:只能精确到秒,毫秒将用0来代替
比如上面代码输出的结果(一眼就能看出区别):
1398250549123
1398250549123
1398250549000 
*/

时间戳转换为时间格式

function getDate(){ 
  let data = "1679294763532";
  var t = new Date(data).toLocaleString(); 
  return t; // "2023/3/20 14:46:03"
}

Vue 中 methods 里去掉function食用,如果写项目的时候methods没有包裹到,就写到外面,

function jsDateFormat(time) {
  var date = new Date(time);
  var year = date.getFullYear();
  var month = date.getMonth() + 1 < 10 ? "0" + (date.getMonth() + 1) : date.getMonth() + 1;
  var day = date.getDate() < 10 ? "0" + date.getDate() : date.getDate();
  var hours = date.getHours() < 10 ? "0" + date.getHours() : date.getHours();
  var minutes = date.getMinutes() < 10 ? "0" + date.getMinutes() : date.getMinutes();
  var seconds = date.getSeconds() < 10 ? "0" + date.getSeconds() : date.getSeconds();
  // 拼接
  return year + "-" + month + "-" + day;
}

猜你喜欢

转载自blog.csdn.net/cdd9527/article/details/128671059