new Date()日期對象

new Date()日期對象

創(chuàng)建Date對象的語法

var now = new Date();  //獲取系統(tǒng)當前時間

注釋:Date 對象會自動把當前日期和時間保存為其初始值

js中單獨調(diào)用new Date()
顯示的結(jié)果是:Mar 31 10:10:43 UTC+0800 2012 這種格式的時間,稱為時間對象
但是用new Date() 參與計算會自動轉(zhuǎn)換為從1970.1.1開始的毫秒數(shù)

new Date()傳參

主要使用以下兩種方式通過傳參創(chuàng)建指定日期Date對象
參數(shù)可以為整數(shù) , 也可以為字符串

var d = new Date(dateString);
var d = new Date(year, month, day, hours, minutes, seconds, milliseconds);

// 當前時間
var date = new Date()
console.log('date--',date)  // date-- Fri May 15 2020 12:17:49 GMT+0800 (中國標準時間)
// 指定時間
var date1 = new Date('2020-03-23')
console.log('date1--',date1)  // Mon Mar 23 2020 08:00:00 GMT+0800 (中國標準時間)

new Date( year, month, date, hrs, min, sec)

按給定的參數(shù)創(chuàng)建一日期對象

參數(shù)說明:
  year的值為:如果年份<2000年,則需設(shè)定的年份減去1900扇住。例如需設(shè)定的年份是1997則year的值應(yīng)為97桨仿,即1997-1900的結(jié)果。所以Date中可設(shè)     定的年份最小為1900筑辨;如果年份>2000年总滩,則year就是該年份表示纲堵。
  month的值域為0~11,0代表1月闰渔,11表代表12月席函;
  date的值域在1~31之間;
  hrs的值域在0~23之間冈涧。從午夜到次日凌晨1點間hrs=0茂附,從中午到下午1點間hrs=12;
  min和sec的值域在0~59之間督弓。
  例 Date day=new Date(11,3,4);
  //day中的時間為:04-Apr-11 12:00:00 AM

new Date( year, month-1, day)

new Date(年份,月份-1,日期)
表示拿到某年某月某日的零點零時零分的標準時間 , 月份要減一 , 參數(shù)為number類型

                console.log('0000---',new Date())

                var now = util.timeFormat(new Date(), 'yyyy-mm-dd')
                console.log('1111---',now)

                now = now.split('-')
                console.log('2222---',now)

                now = new Date(Number(now['0']), (Number(now['1']) - 1), Number(now['2']))
                console.log('3333---',now)

結(jié)果顯示如下


image.png

new Date(year,month,0)

得到某年某月的最后一天的日期對象

new Date(2020,9,0)
// 結(jié)果 
Wed Sep 30 2020 00:00:00 GMT+0800 (中國標準時間)

// 但需要注意getMonth()得到的月份數(shù)值需要 + 1
// 如果不加1 , 則得到的結(jié)果是上個月的最后一天
var d = new Date()
var bg = new Date(d.getFullYear(), d.getMonth(), 0)
console.log('4444---',bg)

// 結(jié)果
4444--- Mon Aug 31 2020 00:00:00 GMT+0800 (中國標準時間)

一 獲取特定格式的時間

now.getYear(); //獲取當前年份(2位)
now.getFullYear()  // 獲取完整的年份 2019
now.getMonth()   //獲取當前月份(0-11,0代表1月)  需要+1
now.getDate()    //獲取當前日(1-31)
now.getDay()     //獲取當前星期X(0-6,0代表星期天)
now.getTime()   //獲取當前時間(從1970.1.1開始的毫秒數(shù))
now.getHours()     //獲取當前小時數(shù)(0-23)
now.getMinutes()    //獲取當前分鐘數(shù)(0-59)
now.getSeconds()   //獲取當前秒數(shù)(0-59)
now.toLocaleDateString()  //獲取當前日期  "2019/1/21"
myDate.getMilliseconds(); //獲取當前毫秒數(shù)(0-999)
myDate.toLocaleDateString(); //獲取當前日期
var mytime=myDate.toLocaleTimeString(); //獲取當前時間
myDate.toLocaleString( ); //獲取日期與時間

二 JavaScript 時間戳

1.js獲取時間戳的幾種方式

時間戳是指格林威治時間1970年01月01日00時00分00秒(北京時間1970年01月01日08時00分00秒)起至現(xiàn)在的總秒數(shù)
返回值都是 1970/1/1 午夜距離該日期時間的毫秒數(shù)
返回數(shù)值單位是毫秒

<1>獲取1970/1/1 午夜到當前時間的時間戳:

1)var now = new Date().getTime()  //返回值都是 1552635602832
2)var now = new Date().valueOf()
3)var now = +new Date()
4) var now = Date.now()
5) var now =Date.parse(new Date())  // 不建議使用  結(jié)果:1552635602000   后三位毫秒改成了000顯示 , 因為parse只能精確到秒

Date.parse(dateVal)雖然聲稱是返回日期與 1970 年 1 月 1 日午夜之間所間隔的毫秒數(shù)营曼,但是實際上返回的是精確到秒的毫秒數(shù),而并非實際的毫秒愚隧。并且這個數(shù)字是非四舍五入的蒂阱,也就是即使是1秒999毫秒,也按照1000毫秒來輸出。
getTime()則返回實際毫秒數(shù)蒜危。

// 具體應(yīng)用
//某個時間段執(zhí)行一段代碼:
if(new Date('11/19/2018 15:30').getTime() < +new Date() && +new Date() < new Date('11/19/2018 18:00').getTime()){ 
// 11/19/2018 15:30  11/19/2018 18:00
        this.isActive = true;  //此處要執(zhí)行的代碼
        this.$apply()
}

<2>獲取自定義時間戳的方法

指定時間戳

1)var old = new Date('2018/03/03').getTime()  //1520006400000
2)var old = new Date('2018/03/03').valueOf()  //1520006400000
3)var old = Date.parse('2018/03/03')   //1520006400000
// 也可以給一個完整的時間(包含時分秒)
4) var timestamp = (new Date(" 2018/06/22 08:00:20")).getTime()

<3>獲得 10 位數(shù)的時間戳

在 JavaScript 中虱痕,通過時間對象轉(zhuǎn)換得到的時間戳都是 13 位的,但有時候我們也需要精確到秒的 10 位時間戳辐赞,比如微信支付用的就是 10 位的時間戳。要在 JavaScript 獲得 10 位的時間戳硝训,大致思路有兩個响委,要么截取前 10 位,要么除以 1000窖梁。示例如下:

// 將 13 位時間戳除以 1000 然后再取整赘风,得到 10 位時間戳數(shù)字
parseInt(+new Date()/1000);

// 將 13 位時間戳轉(zhuǎn)換為字符串截取前 10 位,得到 10 位時間戳字符串
(+new Date()).toString().substring(0,10); // 截取第 0~9 位
(+new Date()).toString().substr(0,10);    // 從第 0 位開始截取 10 位

2. 時間格式字符串轉(zhuǎn)為時間戳(毫秒)

時間戳格式:比如1520006400000 (注意與時間對象的區(qū)別)
時間格式:比如2016-01-01 17:22:37

// 即將字符串形式的日期轉(zhuǎn)換成日期對象

var strTime="2011-04-16";    //字符串日期格式           
var date= new Date(Date.parse(strTime.replace(/-/g,  "/")));      //轉(zhuǎn)換成Data();

var time1=‘2016-01-01 17:22:37’纵刘;  
var date=new Date(time1.replace(/-/g, '/'));  //開始時間  
var time2=date.getTime();  

3.時間對象轉(zhuǎn)換為時間戳

在 JavaScript 中邀窃,將時間對象轉(zhuǎn)換為時間戳的方法有 5 種,示例如下:

// 定義一個時間對象 dt假哎,然后依次演示各種將 dt 轉(zhuǎn)換為時間戳的寫法
var dt = new Date("2019-07-04 23:59:59.999");

// 寫法一瞬捕,精確到毫秒,得到 13 位時間戳 1562255999999
console.log(dt.getTime());

// 寫法二舵抹,精確到毫秒肪虎,得到 13 位時間戳 1562255999999
console.log(dt.valueOf());

// 寫法三,精確到毫秒惧蛹,得到 13 位時間戳 1562255999999
console.log(Number(dt));

// 寫法四扇救,精確到毫秒,得到 13 位時間戳 1562255999999
console.log(+dt);

// 寫法五香嗓,精確到秒迅腔,得到 13 位時間戳 1562255999000,后三位固定為 000
console.log(Date.parse(dt));

4.時間戳轉(zhuǎn)換為時間對象

在 JavaScript 中靠娱,時間戳轉(zhuǎn)時間對象的方法非常簡單沧烈,直接將一個時間戳做為Date的參數(shù)即可,示例如下:

// 注意:參數(shù)中的時間戳必須是 13 位的饱岸,多一位或少一位都不行
new Date(1562169599000);

// 將時間戳轉(zhuǎn)換為更加直觀形象的本地時間
new Date(1562169599000).toLocaleString();
image.png

注意時間戳一定要是int型掺出,否則轉(zhuǎn)換失敗。parseInt()一下最好

5.時間戳轉(zhuǎn)成日期格式

// 方式一
function formatDate(date) {
    var y = date.getFullYear();
    var m = date.getMonth() + 1;
    m = m < 10 ? '0' + m : m;
    var d = date.getDate();
    d = d < 10 ? ('0' + d) : d;
    return y + '-' + m + '-' + d;//這里可以寫格式
    //輸出:2018-03-24
}

// 方式二
function timestampToTime(timestamp) {
    var date = new Date(timestamp * 1000);//時間戳為10位需*1000苫费,時間戳為13位的話不需乘1000
    var Y = date.getFullYear() + '-';
    var M = (date.getMonth()+1 < 10 ? '0'+(date.getMonth()+1) : date.getMonth()+1) + '-';
    var D = date.getDate() + ' ';
    var h = date.getHours() + ':';
    var m = date.getMinutes() + ':';
    var s = date.getSeconds();
    return Y+M+D+h+m+s;
}
timestampToTime(1403058804);
console.log(timestampToTime(1403058804));//2014-06-18 10:33:24

// 方式三
      var formatDateTime3 = function(time, format){  
          var t = new Date(time);  
          var tf = function(i){return (i < 10 ? '0' : '') + i};  
          return format.replace(/yyyy|MM|dd|HH|mm|ss/g, function(a){  
              switch(a){  
                  case 'yyyy':  
                      return tf(t.getFullYear());  
                      break;  
                  case 'MM':  
                      return tf(t.getMonth() + 1);  
                      break;  
                  case 'mm':  
                      return tf(t.getMinutes());  
                      break;  
                  case 'dd':  
                      return tf(t.getDate());  
                      break;  
                  case 'HH':  
                      return tf(t.getHours());  
                      break;  
                  case 'ss':  
                      return tf(t.getSeconds());  
                      break;  
              }  
          })  
      }

6.日期格式轉(zhuǎn)成時間戳

var date = new Date('2014-04-23 18:55:49:123');
// 有三種方式獲取
// 精確到毫秒
var time1 = date.getTime();
console.log(time1);//1398250549123
// 精確到毫秒
var time2 = date.valueOf();
console.log(time2);//1398250549123
// 只能精確到秒汤锨,毫秒用000替代
var time3 = Date.parse(date);
console.log(time3);//1398250549000

三 系統(tǒng)時間格式設(shè)定

1、當前系統(tǒng)區(qū)域設(shè)置格式(toLocaleDateString和toLocaleTimeString)
     例子:(new Date()).toLocaleDateString() + " " + (new Date()).toLocaleTimeString()
     結(jié)果: 2008年1月29日 16:13:11

2.普通字符串(toDateString和toTimeString)
     例子: (new Date()).toDateString() + " " + (new Date()).toTimeString()
     結(jié)果:Tue Jan 29 2008 16:13:11 UTC+0800

3.格林威治標準時間(toGMTString)
     例子: (new Date()).toGMTString()
     結(jié)果:Tue, 29 Jan 2008 08:13:11 UTC

4.全球標準時間(toUTCString)
     例子: (new Date()).toUTCString()
     結(jié)果:Tue, 29 Jan 2008 08:13:11 UTC

5.Date對象字符串(toString)
     例子: (new Date()).toString()
     結(jié)果:Tue Jan 29 16:13:11 UTC+0800 2008

四 日常工作的時間格式相互轉(zhuǎn)化

1.日期格式轉(zhuǎn)為日期標準字符串:比如2015-03-19

// 方式一
var formatDate = function (date) {  
    var y = date.getFullYear();  
    var m = date.getMonth() + 1;  
    m = m < 10 ? '0' + m : m;  
    var d = date.getDate();  
    d = d < 10 ? ('0' + d) : d;  
    return y + '-' + m + '-' + d;  
}

// 方式二
arr.date = new Date();
      var d = new Date(arr.date);
      var yue = (d.getMonth() + 1) > 9 ? (d.getMonth() + 1) : '0' + (d.getMonth() + 1);
      var re = d.getDate() > 9 ? d.getDate() : '0' + d.getDate();
      var youWant = d.getFullYear() + '-' + yue + '-' + re;
      arr.date = youWant;

2. js方法返回值:比如2015-03-19 12:00:00

//方法一
var formatDateTime = function (date) {  
                var y = date.getFullYear();  
                var m = date.getMonth() + 1;  
                m = m < 10 ? ('0' + m) : m;  
                var d = date.getDate();  
                d = d < 10 ? ('0' + d) : d;  
                var h = date.getHours();  
                h=h < 10 ? ('0' + h) : h;  
                var minute = date.getMinutes();  
                minute = minute < 10 ? ('0' + minute) : minute;  
                var second=date.getSeconds();  
                second=second < 10 ? ('0' + second) : second;  
                return y + '-' + m + '-' + d+' '+h+':'+minute+':'+second;  
            }

//方法二
    /**
     * 計算時間返回 yyyy-MM-dd h:m:s 格式的方法
     * timestamp 時間戳
     */
    timestampToTime (timestamp) {
       // 計算年月日時分的函數(shù)
       var date = new Date(timestamp)
       var Y = date.getFullYear() + '-'
       var M = (date.getMonth() + 1) + '-'
       var D = date.getDate() + ' '
       var h = date.getHours() + ':'
       var m = date.getMinutes() + ':'
       var s = date.getSeconds()
       return Y + M + D + h + m + s
   }

3. 日期對象轉(zhuǎn)為字符串日期格式 (yyyymmdd 或 yyyy-mm-dd)

將 Tue Aug 18 2020 00:00:00 GMT+0800 (中國標準時間) 轉(zhuǎn)為 yyyymmdd格式顯示

// 方法一
/**
 * 轉(zhuǎn)換日期格式百框,結(jié)果如20200308
 * @param time  時間格式闲礼,如new Date()  比如Tue Aug 18 2020 00:00:00 GMT+0800 (中國標準時間)
 * @param type  type為1則轉(zhuǎn)換成yyyymmdd格式,type為2則轉(zhuǎn)換成yyyymm格式, type為3時,轉(zhuǎn)換為yyyy-mm-dd
 * @returns {string}
 */
const changeDate = (time, type) => {
  let temp_time = new Number(time)
  let temp_date = new Date(temp_time)
  let temp_year1 = ""
  let temp_month1 = ""
  let temp_day1 = ""
  if (type == 1) {
    temp_year1 = temp_date.getFullYear()
    temp_month1 = (temp_date.getMonth() + 1) > 9 ? (temp_date.getMonth() + 1) : "0" + (temp_date.getMonth() + 1)
    temp_day1 = (temp_date.getDate()) > 9 ? (temp_date.getDate()) : "0" + (temp_date.getDate())
    return temp_year1.toString() + temp_month1.toString() + temp_day1.toString()
  } else if (type == 2) {
    temp_year1 = temp_date.getFullYear()
    temp_month1 = (temp_date.getMonth() + 1) > 9 ? (temp_date.getMonth() + 1) : "0" + (temp_date.getMonth() + 1)
    return temp_year1.toString() + temp_month1.toString()
  } else if (type == 3) {
    temp_year1 = temp_date.getFullYear()
    temp_month1 = (temp_date.getMonth() + 1) > 9 ? (temp_date.getMonth() + 1) : "0" + (temp_date.getMonth() + 1)
    temp_day1 = (temp_date.getDate()) > 9 ? (temp_date.getDate()) : "0" + (temp_date.getDate())
    return temp_year1.toString() + '-' + temp_month1.toString() + '-' + temp_day1.toString()
  }
}

// 使用時
changeDate(val, 3)
這個val就是new Date()得到的時間戳格式  比如Tue Aug 18 2020 00:00:00 GMT+0800 (中國標準時間)

// 方法二
const timeFormat = (value, format) => {
  let date = new Date(value)
  let y = date.getFullYear()
  let m = date.getMonth() + 1
  let d = date.getDate()
  let h = date.getHours()
  let min = date.getMinutes()
  let s = date.getSeconds()
  let result = ''
  if (format == undefined) {
    result = `${y}-${m < 10 ? '0' + m : m}-${d < 10 ? '0' + d : d} ${
      h < 10 ? '0' + h : h
    }:${min < 10 ? '0' + min : min}:${s < 10 ? '0' + s : s}`
  }
  if (format == 'yyyy-mm-dd') {
    result = `${y}-${m < 10 ? '0' + m : m}-${d < 10 ? '0' + d : d}`
  }
  if (format == 'yyyymmdd') {
    result = `${y}${m < 10 ? '0' + m : m}${d < 10 ? '0' + d : d}`
  }
  if (format == 'yyyy-mm') {
    result = `${y}-${m < 10 ? '0' + m : m}`
  }
  if (format == 'mm-dd') {
    result = ` ${mm < 10 ? '0' + mm : mm}:${ddmin < 10 ? '0' + dd : dd}`
  }
  if (format == 'hh:mm') {
    result = ` ${h < 10 ? '0' + h : h}:${min < 10 ? '0' + min : min}`
  }
  if (format == 'yyyy') {
    result = `${y}`
  }
  return result
}

// 使用時
timeFormat(new Date(), 'yyyy-mm-dd')

4.將日期字符串(yyyymmdd)轉(zhuǎn)換成日期對象

var strTime="2011-04-16";    //字符串日期格式            
var date= new Date(Date.parse(strTime.replace(/-/g,  "/")));      //轉(zhuǎn)換成Data(); 
// 結(jié)果-- Sat Apr 16 2011 00:00:00 GMT+0800 (中國標準時間)

5.將日期字符串(yyyy-mm-dd)轉(zhuǎn)換成年月日顯示

const changeDateFormat = (value) => {
  if(value){
    let reg =/(\d{4})\-(\d{2})\-(\d{2})/
    let result = value.replace(reg,"$1年$2月$3日")
    return result
  }
}

// 結(jié)果為2020年08月20日這種格式

6.將年月日日期格式轉(zhuǎn)為其他格式

匹配中文字符的正則表達式: [/u4e00-/u9fa5]

舉例
2021年05月08日 轉(zhuǎn)為 2021-05-08

代碼
var value = str.replace(/[\u4e00-\u9fa5]/g, '-');  // 將漢字替換為 -

7.將日期格式(yyyy-mm-dd)轉(zhuǎn)換成轉(zhuǎn)換為日期字符串(yyyy/MM/dd)或(yyyyMMdd)顯示

replace(/-/g, "/") 和replace(/-/g, " ")的應(yīng)用 : /g 代表全局柬泽,所有的 - 都被替換

<1>轉(zhuǎn)換為yyyy/MM/dd

方式一(推薦)
var bgDate = "2017-02-16"
this.bgDate.replace(/-/g, '/')  

方式二
var str = "2017-02-16"
var reg =/(\d{4})\-(\d{2})\-(\d{2})/
var date = str.replace(reg,"$1/$2/$3")
alert(date)

<2>轉(zhuǎn)換為yyyyMMdd

var bgDate = "2017-02-16"
this.bgDate.replace(/-/g, '')  

8.將日期字符串(yyyymmdd)轉(zhuǎn)換成日期格式(yyyy-mm-dd)

$1表示replace函數(shù)里的占位符

var dateString = '19930701';
var pattern = /(\d{4})(\d{2})(\d{2})/;
var formatedDate = dateString.replace(pattern, '$1-$2-$3');
// 結(jié)果:1993-07-01  

 dateConversion(date) {
      let regExp = new RegExp(/(\d{4})(\d{2})(\d{2})/)
      let pattern = /(\d{4})(\d{2})(\d{2})/
      return date?date.replace(pattern, '$1-$2-$3'):''
    }

五 日期的常用方法

1.setMonth() 和getMonth()

<1>setMonth() 方法用于設(shè)置月份
dateObject.setMonth(month,day)
month   必需慎菲。一個表示月份的數(shù)值,該值介于 0(一月) ~ 11(十二月) 之間锨并。
               -1 為去年的最后一個月
                12 為明年的第一個月
                13 為明年的第二個月

day     可選露该。一個表示月的某一天的數(shù)值,該值介于 1 ~ 31 之間(以本地時間計)第煮。
                0 為上個月的最后一天
                -1 為上個月的最后一天之前的一天

                如果當月有31天:
                32 為下個月的第一天

                如果當月有30天:
                32 為下個月的第二天


setMonth() 方法用于設(shè)置月份解幼。
注意: 一月為 0, 十二月為 11
這個方法可用于設(shè)置月份中的某一天包警。

舉例
設(shè)置月份參數(shù)為 4 (5月份):
var d = new Date();
d.setMonth(4);

d 輸出結(jié)果:
Mon May 04 2020 10:34:46 GMT+0800 (中國標準時間)


bug
只要setMonth()的參數(shù)為小于31天的月份時就會變?yōu)橄乱粋€月撵摆。
原因是:因為當前月份是31天,而設(shè)置的月份小于31天害晦,就會把日期順延特铝。
解決方法:
      1、設(shè)置月份時壹瘟,將日期設(shè)為1鲫剿,記setMonth(month, 1)

<2>getMonth() 方法可返回表示月份的數(shù)字
dateObject.getMonth()
返回值
dateObject 的月份字段,使用本地時間俐筋。返回值是 0(一月) 到 11(十二月) 之間的一個整數(shù)牵素。

2.getDate()和setDate()

<1>getDate()方法可返回月份的某一天
//語法
dateObject.getDate()
dateObject 所指的月份中的某一天,使用本地時間澄者。

返回值是一個月中的某一天, 值為 1 - 31 之間的一個整數(shù)笆呆。

//舉例
var d = new Date()
document.write(d.getDate())  // 比如今天是20200630,返回值為30

var birthday = new Date("July 21, 1983 01:15:00")
document.write(birthday.getDate())    // 輸出21

返回什么日期 取決于d這個變量是什么日期,假如d是20200627 ,則返回值為27
<2>setDate() 方法用于設(shè)置一個月的某一天
//語法
Date.setDate(day)

day 必需。表示一個月中的一天的一個數(shù)值(1 ~ 31):
0 為上一個月的最后一天
-1 為上一個月最后一天之前的一天

如果當月有 31 天:  32 為下個月的第一天
如果當月有 30 天:  32 為下一個月的第二天

//舉例
var d = new Date();
d.setDate(15);
//d 輸出結(jié)果: Mon Jun 15 2020 21:49:03 GMT+0800 (中國標準時間)

3.getTime()和setTime()

<1>getTime()
var now = new Date(); 
now.getTime()   //獲取當前時間(從1970.1.1開始的毫秒數(shù))   =>時間戳
<2>setTime()
Date.setTime(millisec)
// millisec 必需粱挡。表示要設(shè)置的日期和時間據(jù) GMT 時間 1970 年 1 月 1 日午夜之間的毫秒數(shù)赠幕。
// 返回值也是毫秒數(shù)

4.new Date(year,month,0)和new Date(year,month-1,day)

<1>new Date(year,month,0)

表示得到某年某月的最后一天的日期對象

const d = new Date(end.getFullYear(),end.getMonth()+1,0)

示例


image.png

通常用new Date(year,month,0).getDate()計算某月的天數(shù)

//獲取某年某月有多少天
function getMonthLength(year, month) {
    return new Date(year, month, 0).getDate();
}

getMonthLength(2017, 2); //28

參考文章 https://segmentfault.com/q/1010000011402629?sort=created

<2>new Date(year,month-1,day)

new Date(年份,月份-1,日期)
表示拿到某年某月某日的零點零時零分的標準時間 , 月份要減一 , 參數(shù)為number類型

new Date(2020,6,1)  表示拿到七月一號零點零時零分的標準時間
Wed Jul 01 2020 00:00:00 GMT+0800 (中國標準時間)  

new Date (2020,5,22) 表示拿到六月22號零點零時零分的標準時間
Mon Jun 22 2020 00:00:00 GMT+0800 (中國標準時間) 
image.png

六 設(shè)置/獲取時間段

1.JS獲取最近一周的時間

const end = new Date()
const start = new Date()
start.setTime(start.getTime() - 3600 * 1000 * 24 * 7)
const date = [start, end]
date輸出:
0: Wed Jul 10 2019 12:21:48 GMT+0800 (中國標準時間) {}
1: Wed Jul 17 2019 12:21:48 GMT+0800 (中國標準時間) {}

2.JS獲取六個月前到至今的時間段

let end = new Date()
let start = new Date()
start.setTime(start.getTime() - 3600 * 1000 * 24 * 180) // 往前推6個月
this.startDate = utils.changeDate(start, 1)  // 拿到6個月前的日期
this.endDate = utils.changeDate(end, 1)   // 當前日期

// changeDate是個公共方法,將日期轉(zhuǎn)換為yyyy-mm-dd

3.JS獲取當日/三日/近一個月的日期

image.png
<div>
                <div class="left-box">快速查詢</div>
                <div class="right-box quick_query">
                    <div v-for="(item,index) in Lists" :key="index" :class="{choose_item:name == item.name}" @click="Choose(item,index)">
                        {{item.name}}
                        <img src="@/assets/image/company/xuanze.png" class="check_icon" v-show="item.name == name" />
                    </div>
                </div>
</div>


data(){
  return{
      Lists: [
                {name: '當日'},
               {name: '三日'},
               {name: '近一月'}
        ],
     name: '',
   }
}
// 快速查詢選擇
            Choose(item, index) {
                var now = util.timeFormat(new Date(), 'yyyy-mm-dd')
                now = now.split('-')
                now = new Date(Number(now['0']), (Number(now['1']) - 1), Number(now['2']))  // 獲取當前日期的零點零時的標準時間
                var d = new Date()
                var bg = new Date(d.getFullYear(), d.getMonth(), 0) // 獲取上個月最后一天的day
                bg = bg.getDate()
                if(index === 0) {
                    this.bgDate = util.timeFormat(new Date(), 'yyyy-mm-dd')
                    this.endDate = util.timeFormat(new Date(), 'yyyy-mm-dd')
                } else if(index === 1) {
                    now = util.timeFormat(now.setDate(now.getDate() - 2), 'yyyy-mm-dd')

                    this.bgDate = now;
                    this.endDate = util.timeFormat(new Date(), 'yyyy-mm-dd')
                } else if(index === 2) {
                    now = util.timeFormat(now.setDate(now.getDate() - bg), 'yyyy-mm-dd')
                    this.bgDate = now;
                    this.endDate = util.timeFormat(new Date(), 'yyyy-mm-dd')
                }
                this.name = item.name
            },
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末,一起剝皮案震驚了整個濱河市询筏,隨后出現(xiàn)的幾起案子榕堰,更是在濱河造成了極大的恐慌,老刑警劉巖嫌套,帶你破解...
    沈念sama閱讀 218,386評論 6 506
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件逆屡,死亡現(xiàn)場離奇詭異,居然都是意外死亡踱讨,警方通過查閱死者的電腦和手機魏蔗,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 93,142評論 3 394
  • 文/潘曉璐 我一進店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來痹筛,“玉大人莺治,你說我怎么就攤上這事廓鞠。” “怎么了谣旁?”我有些...
    開封第一講書人閱讀 164,704評論 0 353
  • 文/不壞的土叔 我叫張陵床佳,是天一觀的道長。 經(jīng)常有香客問我榄审,道長砌们,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 58,702評論 1 294
  • 正文 為了忘掉前任瘟判,我火速辦了婚禮怨绣,結(jié)果婚禮上,老公的妹妹穿的比我還像新娘拷获。我一直安慰自己,他們只是感情好减细,可當我...
    茶點故事閱讀 67,716評論 6 392
  • 文/花漫 我一把揭開白布匆瓜。 她就那樣靜靜地躺著,像睡著了一般未蝌。 火紅的嫁衣襯著肌膚如雪驮吱。 梳的紋絲不亂的頭發(fā)上,一...
    開封第一講書人閱讀 51,573評論 1 305
  • 那天萧吠,我揣著相機與錄音左冬,去河邊找鬼。 笑死纸型,一個胖子當著我的面吹牛拇砰,可吹牛的內(nèi)容都是我干的。 我是一名探鬼主播狰腌,決...
    沈念sama閱讀 40,314評論 3 418
  • 文/蒼蘭香墨 我猛地睜開眼除破,長吁一口氣:“原來是場噩夢啊……” “哼!你這毒婦竟也來了琼腔?” 一聲冷哼從身側(cè)響起瑰枫,我...
    開封第一講書人閱讀 39,230評論 0 276
  • 序言:老撾萬榮一對情侶失蹤,失蹤者是張志新(化名)和其女友劉穎丹莲,沒想到半個月后光坝,有當?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體,經(jīng)...
    沈念sama閱讀 45,680評論 1 314
  • 正文 獨居荒郊野嶺守林人離奇死亡甥材,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點故事閱讀 37,873評論 3 336
  • 正文 我和宋清朗相戀三年盯另,在試婚紗的時候發(fā)現(xiàn)自己被綠了。 大學時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片擂达。...
    茶點故事閱讀 39,991評論 1 348
  • 序言:一個原本活蹦亂跳的男人離奇死亡土铺,死狀恐怖胶滋,靈堂內(nèi)的尸體忽然破棺而出,到底是詐尸還是另有隱情悲敷,我是刑警寧澤究恤,帶...
    沈念sama閱讀 35,706評論 5 346
  • 正文 年R本政府宣布,位于F島的核電站后德,受9級特大地震影響部宿,放射性物質(zhì)發(fā)生泄漏。R本人自食惡果不足惜瓢湃,卻給世界環(huán)境...
    茶點故事閱讀 41,329評論 3 330
  • 文/蒙蒙 一理张、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧绵患,春花似錦雾叭、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,910評論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至筏勒,卻和暖如春移迫,著一層夾襖步出監(jiān)牢的瞬間,已是汗流浹背管行。 一陣腳步聲響...
    開封第一講書人閱讀 33,038評論 1 270
  • 我被黑心中介騙來泰國打工厨埋, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留,地道東北人捐顷。 一個月前我還...
    沈念sama閱讀 48,158評論 3 370
  • 正文 我出身青樓荡陷,卻偏偏與公主長得像,于是被迫代替她去往敵國和親套菜。 傳聞我的和親對象是個殘疾皇子亲善,可洞房花燭夜當晚...
    茶點故事閱讀 44,941評論 2 355