js 获取指定时间+时间戳展示时分秒

开发中遇见了一个客户比较扯淡的需求
明明有可以选择时分秒的操作非不要就要懒省事,必须是一个时间显示成选中的年月日,但是时间格式要给后端传待时分秒的格式,列表展示也要带时分秒。
所以就处理了

 let DATE: any = new Date(); // 当前日期
 let timestamp = Date.parse(DATE);
 let now = new Date(timestamp);
 console.log(timestamp);

在这里插入图片描述

 function getData(n) {
	  let now = new Date(n),
	    y = now.getFullYear(),
	    m = now.getMonth() + 1,
	    d = now.getDate();
	  return y + "-" + (m < 10 ? "0" + m : m) + "-" + (d < 10 ? "0" + d : d) + " " + now.toTimeString().substr(0, 8);
}
getData(1691031289000) // 

在这里插入图片描述上述封装了一个简单的日期转换,就足够用了
然后就是处理日期拼接。发现我们只要时分秒就可以了。

处理为: 选中的时间 + " " + 选中的时间.toTimeString().substr(0, 8); 即是我们要的时间。

选中的时间 + " " + 选中的时间.toTimeString().substr(0, 8); 即是我们要的时间。


if ('cgTime' in changedFields) { // 判断是否点击了时间弹框,如果点击了就可以拿到选中的时间,如果没有就设置为空
  let cgTime = ''; // 选中的时间初始为空
  let DATE: any = new Date();
  const timestamp = Date.parse(DATE);
  let now = new Date(timestamp);
  if (changedFields.cgTime) {
    cgTime = changedFields.cgTime + ' ' + now.toTimeString().substr(0, 8);
    console.log(cgTime, 'cgTimecgTimecgTime');
  } else {
    this.formRef.setFieldsValue({
      cgTime: null,
    });
  }
  this.formRef.setFieldsValue({
    cgTime,
  });
}

猜你喜欢

转载自blog.csdn.net/lzfengquan/article/details/132078803