美文网首页
JS 时间转换

JS 时间转换

作者: 三石青韦 | 来源:发表于2019-11-19 17:47 被阅读0次

JS中没有格式化字符串的功能,因此在此整理一下,免得总需要网上查询:
我们可以采用给Date添加prototype的方式,也可以单独使用字符串的方式来,其实内部功能是一样的。

prototype 方式

// 对Date的扩展,将 Date 转化为指定格式的String
// 月(M)、日(d)、小时(h)、分(m)、秒(s)、季度(q) 可以用 1-2 个占位符, 
// 年(y)可以用 1-4 个占位符,毫秒(S)只能用 1 个占位符(是 1-3 位的数字) 
// 例子: 
// (new Date()).Format("yyyy-MM-dd hh:mm:ss.S") ==> 2006-07-02 08:09:04.423 
// (new Date()).Format("yyyy-M-d h:m:s.S")      ==> 2006-7-2 8:9:4.18 
Date.prototype.Format = function (fmt) { //author: meizz 
    var o = {
        "M+": this.getMonth() + 1, //月份 
        "d+": this.getDate(), //日 
        "h+": this.getHours(), //小时 
        "m+": this.getMinutes(), //分 
        "s+": this.getSeconds(), //秒 
        "q+": Math.floor((this.getMonth() + 3) / 3), //季度 
        "S": this.getMilliseconds() //毫秒 
    };
    if (/(y+)/.test(fmt)) fmt = fmt.replace(RegExp.$1, (this.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;
}
调用: 

var time1 = new Date().Format("yyyy-MM-dd");
var time2 = new Date().Format("yyyy-MM-dd HH:mm:ss"); 

直接调用方式

// 因为单独函数,需要格式化的日期必须单独传入,第一个参数是日期,第二个参数与上面一样
function dateFormatter(d, fmt) {
  const date = new Date(d);
  const o = {
    'M+': date.getMonth() + 1, // 月份
    'd+': date.getDate(), // 日
    'h+': date.getHours(), // 小时
    'm+': date.getMinutes(), // 分
    's+': date.getSeconds(), // 秒
    'q+': Math.floor((date.getMonth() + 3) / 3), // 季度
    'S': date.getMilliseconds() // 毫秒
  };
  if (/(y+)/.test(fmt)) fmt = fmt.replace(RegExp.$1, (date.getFullYear() + '').substr(4 - RegExp.$1.length));
  for (const 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;
}

调用:
dateFormatter(new Date(), 'yyyy-MM-dd');

相关文章

  • JS 时间转换

    JS中没有格式化字符串的功能,因此在此整理一下,免得总需要网上查询:我们可以采用给Date添加prototype的...

  • js - 时间转换

    1. 本地时间(日期或者毫秒值)转换成UTC时间 参数说明:date: string | number;参数示例:...

  • js对日期的转换

    ## 前言 不清楚js对日期时间怎么转换的,可以参考以下代码 。 ### js日期格式转换 * 字符串变时间 ``...

  • 《Vue.js实战》学习笔记 -时间转换指令

    Vue.js实战 时间转换指令

  • Js Util工具集

    JSON 数据还原 防止后台JSON转换异常 POST提交 时间转换JS 具体时间转换 精确到秒 具体时间 精确到...

  • JS时间格式转换(今天,昨天,前天)

    参考: javascript时间格式转换(今天,昨天,前天) js时间戳与日期格式之间相互转换

  • 时间戳转换

    由于经常需要用的到时间戳转换,后台传过来的数据可能是时间戳,js需要转换成时间 js方法 functiontoDa...

  • js的时间转换:

    将时间戳转换成Date对象(10位的话直接加三个零) 在调试模式下直接console.log(newDate);即...

  • JS 时间格式转换

    方便自己使用

  • JS 时间格式转换

    ``` 传入的参数格式为 yyyy-MM-dd hh:mm:ss 用正则替换后仅显示天数dd 代码如下 let s...

网友评论

      本文标题:JS 时间转换

      本文链接:https://www.haomeiwen.com/subject/ujdgictx.html