关于Date对象的一系列转换及常用方法

9次阅读

共计 2985 个字符,预计需要花费 8 分钟才能阅读完成。

我发现我们在项目中经常会遇到一系列关于时间的操作,比如计算两日期之间的相差天数等等,因此我打算好好整理一下,便于之后的项目会用到。
Date 对象:用于处理日期和时间
一、创建 Date 对象

var date1=new Date();// 参数无,默认当前时间
var date2=new Date(num);// 参数为数字,返回 1970-01-01 08:00:00+num(num 为毫秒)
var date3=new Date(string);// 参数为 string,返回对应的时间
var date4=new Date(year, month, day, hours, minutes, seconds, milliseconds);// 参数为年 - 月 - 日 - 时 - 分 - 秒 - 毫秒,返回对应的时间


二、自身的常用方法
1. 获取

date1.getDate();// 获取当前天数       date1.getDay();// 获取当前星期几 
date1.getFullYear();// 获取当前年份   date1.getHours();// 获取当前小时数
date1.getMinutes();// 获取当前分钟数  date1.getMilliseconds();// 获取当前毫秒数    
date1.getMonth();// 获取当前月份 -1      date1.getSeconds();// 获取当前秒数
date1.getTime();// 获取从 1970-01-01 到当前的毫秒数

2. 设置

date1.setDate(num);// 设置当前天数       date1.setFullYear(num);// 设置当前年份   
date1.setHours(num);// 设置当前小时数    date1.setMinutes(num);// 设置当前分钟数  
date1.setMonth(num);// 设置当前月份      date1.setMilliseconds(num);// 设置当前毫秒数 
date1.setSeconds(num);// 设置当前秒数    date1.setTime(num);// 返回 1970-01-01+num(num 为毫秒)

3. 转换

date1.toDateString();// 将日期部分转换成字符串      date1.toJSON();// 将日期部分转换成 JSON
date1.toLocaleDateString();// 根据本地时间格式,把 Date 对象的日期部分转换为字符串。date1.toLocaleTimeString();// 根据本地时间格式,把 Date 对象的时间部分转换为字符串。date1.toLocaleString();//// 根据本地时间格式,把 Date 对象转换为字符串。date1.toTimeString();// 将时间部分转换成字符串

时间与时间戳的转换
我们要明白这两者之间的关系,参考关于时间的一切(时间戳、Date、表示时间的标准等)

1,Unix 时间戳(Unix timestamp)定义为从 1970 年 01 月 01 日 00 时 00 分 00 秒 (UTC) 起至现在经过的 总秒数
2,JavaScript 中提供的 Date 对象可以将所有时间都存为一个整数(new Date(num)),表示从 1970 年 1 月 1 日 00:00:00 起的 总毫秒数
这两点意味着:
1)使用 unix 时间戳作为参数需要乘以 1000 得到毫秒数 Date()对象才能正确接收,getTime 时需要除以 1000 才能得到时间戳。
2)js 中判断一个时间戳的精度,可以靠时间戳长度:精确到秒是 10 位;精确到毫秒是 13 位。
3)在 js 中利用时间戳很容易计算出一个间隔恒定的时间轴,或者给一个时间推算出某段时间之前 or 之后的具体日期,或者日期比较

相关实例
1、 将 Date 转化为指定格式的 String

// 月(M)、日(d)、小时(h)、分(m)、秒(s)、季度(q) 可以用 1-2 个占位符,// 年 (y) 可以用 1-4 个占位符,毫秒 (S) 只能用 1 个占位符(是 1-3 位的数字)
 Date.prototype.Format = function (fmt) { 
    var o = {"m+": this.getMonth() + 1, // 月份
        "d+": this.getDate(), // 日
        "h+": this.getHours(), // 小时
        "i+": 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;
}
(new Date()).Format("yyyy-mm-dd hh:ii:ss.S");//2019-11-08 17:36:11.2
// 正则表达式中 y 只是一个普通文本,用于匹配字母 y
// y+ 的意思是:匹配 1 个到多个 y
// (y+)的意思是:y+ 匹配到的内容可能通过分组来取到,这里是通过第一个分组取到。从后面的代码中可以看出,RegExp.$1 就是取到的 y + 匹配到的内容

2、获取当前的前几天或后几天的时间

 Date.prototype.AddDays = function (num) {if (isNaN(num) || num === null) {return this;}
  return new Date(this.getTime() + 24 * 60 * 60 * 1000 * num);
}
(new Date()).AddDays(-1).Format("yyyy-mm-dd")//2019-11-07
(new Date()).AddDays(2).Format("yyyy-mm-dd")//2019-11-10

3、计算两日期之间的时间差

function differenceTime(date1,date2) {var a=new Date(date1).getTime();
    var b=new Date(date2).getTime();
    iDays = parseInt(Math.abs(a - b) / 1000 / 60 / 60 / 24); // 把相差的毫秒数转换为天数,Math.abs 是取绝对值
    return iDays;
  }
differenceTime('2019-09-10','2019-10-10')//30

4、比较两个时间的前后

//true---> d1>d2,d1 在 d2 之后,false--->d1<d2,d1 在 d2 之前
function CompareDate(d1, d2) {return ((new Date(d1.replace(/-/g, "\/"))) > (new Date(d2.replace(/-/g, "\/"))));
}
 CompareDate('2019-11-11 12:22','2018-11-11 12:22')//true

正文完
 0