时间格式化

博主分享了自己总结的时间格式化内容,虽可能存在不足,但较为实用。提到模板大致相同,且可能还有未涵盖的情况,同时说明了调用方法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

自己总结的一些时间格式化,可能比较娄,但是还挺好用的

//日期格式化2018-9-9变成2018-09-09与前几天日期
export function getDay(num, str) {
  let today = new Date();
  let nowTime = today.getTime();
  let ms = 24 * 3600 * 1000 * num;
  today.setTime(parseInt(nowTime + ms));
  let oYear = today.getFullYear();
  let oMoth = (today.getMonth() + 1).toString();
  if (oMoth.length <= 1) oMoth = '0' + oMoth;
  let oDay = today.getDate().toString();
  if (oDay.length <= 1) oDay = '0' + oDay;
  return oYear + str + oMoth + str + oDay;
}


//时间补0
export function fillZero(num) {
  if (parseInt(num) < 10) {
    num = '0' + num;
  }
  return num;
}

//时间戳转换13位数
export function transDate(str) {
  let oDate = new Date(str),
    oYear = oDate.getFullYear(),
    oMonth = oDate.getMonth() + 1,
    oDay = oDate.getDate(),
    oHour = oDate.getHours(),
    Minutes = oDate.getMinutes(),
    oTime = fillZero(oYear) + '-' + fillZero(oMonth) + '-' + fillZero(oDay) + ' ' + fillZero(oHour) + ':' + fillZero(Minutes) //最后拼接时间
  return oTime;
}

// 时间转换为2018-03-09 10:20:00 
export function transDateTime(str) {
  let oDate = new Date(str),
    oYear = oDate.getFullYear(),
    oMonth = oDate.getMonth() + 1,
    oDay = oDate.getDate(),
    oHour = oDate.getHours(),
    Minutes = oDate.getMinutes(),
    second = oDate.getSeconds(),
    oTime = fillZero(oYear) + '-' + fillZero(oMonth) + '-' + fillZero(oDay) + ' ' + fillZero(oHour) + ':' + fillZero(Minutes) + ':' + fillZero(second) //最后拼接时间
  return oTime;
}

//时间戳转换10位数
export function transDates(str) {
  let oDate = new Date(str * 1000),
    oYear = oDate.getFullYear(),
    oMonth = oDate.getMonth() + 1,
    oDay = oDate.getDate(),
    oTime = fillZero(oYear) + '年' + fillZero(oMonth) + '月' + fillZero(oDay) + "日"; //最后拼接时间
  return oTime;
}

//时间戳模板2018-09-08
export function DateTemp(str) {
  let oDate = new Date(str),
    oYear = oDate.getFullYear(),
    oMonth = oDate.getMonth() + 1,
    oDay = oDate.getDate(),
    oTime = fillZero(oYear) + '-' + fillZero(oMonth) + '-' + fillZero(oDay); //最后拼接时间
  return oTime;
}

//时间戳模板2018.09.08
export function DateSave(str) {
  let oDate = new Date(str),
    oYear = oDate.getFullYear(),
    oMonth = oDate.getMonth() + 1,
    oDay = oDate.getDate(),
    oTime = fillZero(oYear) + '.' + fillZero(oMonth) + '.' + fillZero(oDay); //最后拼接时间
  return oTime;
}

模板也许都差不多 还能还有其他情况我没有写上去
调用的方法

//就假设这几种吧  其他的自己可以试试看
DateSave(new Date())
transDateTime(new Date())
DateTemp(new Date())
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值