格式化时间的方法集合

1、使用补零函数进行格式化


1. 封装时间格式化函数
//定义格式化时间的函数
function formatDate(dateStr) {
    const date = new Date(dateStr)
    const year = date.getFullYear()
    const month = padZero(date.getMonth() + 1)
    const day = padZero(date.getDate())
    const h = padZero(date.getHours())
    const m = padZero(date.getMinutes())
    const s = padZero(date.getSeconds())
    return `${year}-${month}-${day} ${h}:${m}:${s}`
}

//补零函数
function padZero(n) {
    return n < 10 ? '0' + n : n
}

2、使用ES6语法之padStart(方法)

const formatDate = function (v) {
  let date = new Date(v)
  if (Number.isNaN(Number(date))) {
    date = new Date()
  }
  let y = date.getFullYear()
  let mon = (date.getMonth() + 1 + '').padStart(2, '0')
  let d = (date.getDate() + '').padStart(2, '0')
  let h = (date.getHours() + '').padStart(2, '0')
  let min = (date.getMinutes() + '').padStart(2, '0')
  let s = (date.getSeconds() + '').padStart(2, '0')
  return [y, mon, d].join('-') + ' ' + [h, min, s].join(':')
}

3、获取当前时间距离初始时间的时间戳

// 获得系统时间
let date = new Date()
console.log(date) // Thu Apr 28 2022 17:34:10 GMT+0800 (中国标准时间)
// 距离1970年1月1日 过了多少秒   获得总的毫秒数(时间戳)
// 通过valueOf()    getTime()
let date3 = new Date();
console.log(date3.valueOf())
console.log(date3.getTime())
// 简单写法
let date4 = +new Date(); //+new Date(); 就是获取总的毫秒数
console.log(date4)
// H5新增的方法
 console.log(Date.now())

Date.parse()把字符串转换为Date对象 ,然后返回此Date对象与'1970/01/01 00:00:00'之间的毫秒值
(北京时间的时区为东8区,起点时间实际为:'1970/01/01 08:00:00')
Date.parse('2022-2-28')

// 35天后是周几
let fn4 = () => {
let date = new Date()
let day = date.getDate()
console.log(day)
date.setDate(day + 35)
console.log(date)
 }
fn4()

4、适用于倒计时案例

//倒计时案例
countDown() //先调用一次这个函数,防止刷新的时候有空白
setInterval(countDown, 1000)
// 日期的格式化
function countDown(v) {
   let inputTime = +new Date('2023-5-5 17:00:00'); //返回的是用户输入时间的总的毫秒数
   let nowTime = +new Date(); //返回的是当前时间总的毫秒数
   let times = (inputTime - nowTime) / 1000; //times是剩余时间总的秒数
   d = (parseInt(times / 60 / 60 / 24) + '').padStart(2, '0') //天
   h = (parseInt(times / 60 / 60 % 24) + '').padStart(2, '0') //时
   m = (parseInt(times / 60 % 60) + '').padStart(2, '0') //分
   s = (parseInt(times % 60) + '').padStart(2, '0') //秒
   let str = d + '天' + h + '时' + m + '分' + s + '秒'
   box.innerHTML = str
   }

5、复杂格式化时间结合正则

// 时间格式化
  dateFormat(time, fmt) {
    if (!time) return ''
    if (typeof time === 'string' && time.includes('T')) {
      time = time.replace('T', ' ').replace(/\-/g, '/');
    };

    time = new Date(time);
    var o = {
      'M+': time.getMonth() + 1,
      'd+': time.getDate(),
      'h+': time.getHours(),
      'm+': time.getMinutes(),
      's+': time.getSeconds(),
      'q+': Math.floor((time.getMonth() + 3) / 3),
      'S': time.getMilliseconds()
    }

    if (/(y+)/.test(fmt)) fmt = fmt.replace(RegExp.$1, (time.getFullYear() + '').substr(4 - RegExp.$1.length))
    for (var k in o) {
      if (new RegExp('(' + k + ')').test(fmt)) fmt = fmt.replace(RegExp.$1, (RegExp.$1.length === 1) ? (o[k]) : (('00' + o[k]).substr(('' + o[k]).length)))
    }

    return fmt;
  },

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
你可以使用Java中的SimpleDateFormat类来进行日期格式转换。下面是一个示例代码,将日期集合中的日期格式从一种格式转换为另一种格式: ```java import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; import java.util.List; public class DateConversionExample { public static void main(String[] args) { // 原始日期格式 SimpleDateFormat originalFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); // 目标日期格式 SimpleDateFormat targetFormat = new SimpleDateFormat("dd/MM/yyyy"); // 原始日期集合 List<String> originalDates = new ArrayList<>(); originalDates.add("2022-01-01 10:30:00"); originalDates.add("2022-02-15 15:45:00"); originalDates.add("2022-03-20 08:00:00"); // 转换后的日期集合 List<String> convertedDates = new ArrayList<>(); for (String originalDate : originalDates) { try { // 解析原始日期字符串为Date对象 Date date = originalFormat.parse(originalDate); // 格式化Date对象为目标日期格式的字符串 String convertedDate = targetFormat.format(date); convertedDates.add(convertedDate); } catch (ParseException e) { e.printStackTrace(); } } // 打印转换后的日期集合 for (String convertedDate : convertedDates) { System.out.println(convertedDate); } } } ``` 上述代码中,我们使用SimpleDateFormat类来定义原始日期格式和目标日期格式。然后,我们遍历原始日期集合,将每个日期字符串解析为Date对象,然后再将其格式化为目标日期格式的字符串。最后,我们打印转换后的日期集合。 请根据你的具体需求修改代码中的日期格式和日期集合。希望对你有帮助!

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值