博客
关于我
JS日期格式转换
阅读量:466 次
发布时间:2019-03-06

本文共 1825 字,大约阅读时间需要 6 分钟。

日期与时间戳处理指南

1. 日期与时间戳转换

将时间戳或带格式的日期转换为标准格式。

  • 示例1:2015-11-11
    使用 new Date('2015-11-11') 转换为标准格式:Mon Nov 11 2015 08:00:00 GMT+0800 (中国标准时间)。
  • 示例2:1515260000000
    使用 new Date(1515260000000) 转换为标准格式:Sat Sep 01 2018 08:00:00 GMT+0800 (中国标准时间)。

2. 将时间戳转换为指定格式

如何将时间戳转换为特定格式(如 yyyy-MM-dd hh:mm:ssyyyy-MM-dd)?

  • 使用以下方法:

    // 日期格式化方法  function parseTimeNew(date) {    const ndate = new Date(date);    const type = 'yyyy-MM-dd';    const o = {      'M+': ndate.getMonth() + 1,      'd+': ndate.getDate(),      'h+': ndate.getHours(),      'm+': ndate.getMinutes(),      's+': ndate.getSeconds(),      'q+': Math.floor((ndate.getMonth() + 3) / 3),      'S': ndate.getMilliseconds()    };    if (/(y+)/.test(type)) {      type = type.replace(/(y+)/, (ndate.getFullYear() + '').substr(4 - RegExp.$1.length));    }    for (const k in o) {      if (new RegExp('(' + k + ')').test(type)) {        type = type.replace(RegExp.$1, (RegExp.$1.length === 1) ? o[k] : (('00' + o[k]).substr(('' + o[k]).length));      }    }    return type;  }
  • 使用方法:

    parseTimeNew(1842760000000); // 将时间戳转换为 `yyyy-MM-dd` 格式

3. 判断日期是否为昨天

如何判断给定日期是否为昨天?

  • 方法示例
    // 判断日期是否为昨天  function isYestday(theDate) {    const date = new Date();    const today = new Date(date.getFullYear(), date.getMonth(), date.getDate()).getTime();    const yestday = new Date(today - 24 * 3600 * 1000).getTime();    return theDate.getTime() < today && yestday <= theDate.getTime();  }
  • 调用示例
    const time = new Date('2013-11-11');  isYestday(time); // 返回 `false`,表示 `time` 不是今天

4. 获取今天0点和23:59分的时间戳

如何获取今天0点和23:59分的时间戳?

  • 代码示例
    const todayDate = new Date(new Date().toLocaleDateString());  const startTime1 = new Date(todayDate.getTime()); // 当天0点  const endTime1 = new Date(todayDate.getTime() + 24 * 60 * 60 * 1000 - 1); // 当天23:59

总结

通过以上方法,可以轻松实现日期与时间戳的转换与处理。这些方法适用于多种场景,如数据分析、日志记录等,能够帮助您高效管理时间相关的业务逻辑。

转载地址:http://hagfz.baihongyu.com/

你可能感兴趣的文章
Object.defineProperty详解
查看>>
Object.keys()的详解和用法
查看>>
objectForKey与valueForKey在NSDictionary中的差异
查看>>
Objective - C 小谈:消息机制的原理与使用
查看>>
OBJECTIVE C (XCODE) 绘图功能简介(转载)
查看>>
Objective-C ---JSON 解析 和 KVC
查看>>
Objective-C 编码规范
查看>>
Objective-Cfor循环实现Factorial阶乘算法 (附完整源码)
查看>>
Objective-C——判断对象等同性
查看>>
objective-c中的内存管理
查看>>
Objective-C之成魔之路【7-类、对象和方法】
查看>>
Objective-C享元模式(Flyweight)
查看>>
Objective-C以递归的方式实现二叉搜索树算法(附完整源码)
查看>>
Objective-C内存管理教程和原理剖析(三)
查看>>
Objective-C实现 Greedy Best First Search最佳优先搜索算法(附完整源码)
查看>>
Objective-C实现 jugglerSequence杂耍者序列算法 (附完整源码)
查看>>
Objective-C实现 lattice path格子路径算法(附完整源码)
查看>>
Objective-C实现1000 位斐波那契数算法(附完整源码)
查看>>
Objective-C实现2 个数字之间的算术几何平均值算法(附完整源码)
查看>>
Objective-C实现2d 表面渲染 3d 点算法(附完整源码)
查看>>