js中对时间的操作

我们先来看一下如何获取当前时间:

var date = new Date()
//输出:Tue Jul 02 2019 10:36:22 GMT+0800 (中国标准时间)

紧接着,我们来获取相关参数

var date = new Date();
    console.log("今天的日期是:" + date)
    //今天的日期是:Tue Jul 02 2019 10:43:55 GMT+0800 (中国标准时间)
    var year = date.getFullYear(); //获取当前年份
    console.log("今年是:" + year)
    // 今年是:2019
    var mon = date.getMonth() + 1; //获取当前月份  
    console.log("这个月是:" + mon)
    // 这个月是:7
    var day = date.getDate(); //获取当前日  
    console.log("今天是这个月的第" + day + "天")
    // 今天是这个月的第2天
    var weekday = date.getDay(); //获取当前星期几  
    console.log("今天是这周的第" + weekday + "天")
    // 今天是这周的第2天
    var h = date.getHours(); //获取小时  
    console.log("现在是:" + h + "点")
    // 现在是:10点
    var m = date.getMinutes(); //获取分钟  
    console.log("当前是这个小时:" + m + "分钟")
    // 当前是这个小时:43分钟
    var s = date.getSeconds(); //获取秒  
    console.log("当前是这个分种:" + s + "秒")
    // 当前是这个分种:55秒  

以上大概就是js中获取相应时间参数的所有方法了吧。
不过,很多时候,我们是要用到计算两个时间差的,经常会因为格式不匹配而出现各种问题,我们只要记住 三点:

  • 字符串之间是不能做数学运算的
  • 做差的两个类型是相同的,也就是Date对象和Date对象,时间戳(long)和时间戳
    请看以下:

    1.将其他格式转为Date对象

通过传入一个会被JavaScript解析的字符串来构造
console.log(new Date('September 7, 2018'))  // Fri Sep 07 2018 00:00:00 GMT+0800 (中国标准时间)
console.log(new Date('September 7, 2018, GMT+0800'))  // Fri Sep 07 2018 00:00:00 GMT+0800 (中国标准时间)

通过传入一个毫秒数来构造
// 从Unix新纪元的时间创建日期
console.log(new Date(0))  // Thu Jan 01 1970 08:00:00 GMT+0800 (中国标准时间)
console.log(new Date(10000))  // Thu Jan 01 1970 08:00:10 GMT+0800 (中国标准时间)
console.log(new Date(1536307550023))  // Fri Sep 07 2018 16:05:50 GMT+0800 (中国标准时间)
// 使用负数创建新纪元之前的日期
console.log(new Date(-1536307550023))  // Tue Apr 26 1921 23:54:09 GMT+0800 (中国标准时间)

通过传入一个特定的本地日期来构造
总的来说格式为: new Date(年, 月, 日, 时, 分, 秒)
// 月份是从0开始的,一月为0,二月为1,九月为8等等
console.log(new Date(2018, 8))  // Sat Sep 01 2018 00:00:00 GMT+0800 (中国标准时间)
console.log(new Date(2018, 8, 7))  // Fri Sep 07 2018 00:00:00 GMT+0800 (中国标准时间)
console.log(new Date(2018, 8, 7, 16))  // Fri Sep 07 2018 16:00:00 GMT+0800 (中国标准时间)
console.log(new Date(2018, 8, 7, 16, 7))  // Fri Sep 07 2018 16:07:00 GMT+0800 (中国标准时间)
console.log(new Date(2018, 8, 7, 16, 7, 50))  // Fri Sep 07 2018 16:07:50 GMT+0800 (中国标准时间)
console.log(new Date(2018, 8, 7, 16, 7, 50, 23))  // Fri Sep 07 2018 16:07:50 GMT+0800 (中国标准时间)

以上部分代码转自简书,如有侵权,请联系删除

最后再说一个将时间本地化的方法

var date = new Date();
date.toLocaleString('zh-Hans-CN', {
    timeZone: "Asia/Beijing", 
    hourCycle: "h24",
    weekday: 'long', 
    year: 'numeric', 
    month: 'long', 
    day: 'numeric',
    hour: 'numeric',
    minute: 'numeric',
    second: 'numeric'
})

以上部分代码转自github,如有侵权,请联系删除

猜你喜欢

转载自www.cnblogs.com/Lyn4ever/p/11119350.html