JavaScript 常用日期(Date)转换

整理一些比较常用的日期格式转换function

1.日期格式化(转年月日时分秒)

 //日期格式化(转年月日时分秒)
  dateFormat:function(datetime){
    let date = new Date(datetime);
    let year = date.getFullYear();
    let month = date.getMonth() + 1;
    let day = date.getDate();
    let hour = date.getHours();
    let minute = date.getMinutes();
    let second = date.getSeconds();
    return year + "-" + this.formatTen(month) + "-" + this.formatTen(day)+ " " +this.formatTen(hour)+ ":" +this.formatTen(minute)+ ":" +this.formatTen(second);
  },
  formatTen:function (num) {
    return num > 9 ? (num + "") : ("0" + num);
  }

2.获取n个月前的第一天

 //n个月前的第一天
  monthStartDay:function (n) {
    let today = new Date();
    today.setMonth(today.getMonth()-n);
    let y = today.getFullYear();
    let m = today.getMonth()+1;
    return  y+'-'+this.formatTen(m)+'-01';
  },
  formatTen:function (num) {
    return num > 9 ? (num + "") : ("0" + num);
  },

3.获取近n个月的开始时间(n=6 近六个月)

  //获取近n个月的开始时间
  getMonthDay:function(n){
    let today = new Date();
    today.setMonth(today.getMonth()-n);
    let y = today.getFullYear();
    let m = today.getMonth()+1;
    let d = today.getDate();
    return  y+'-'+this.formatTen(m)+'-'+this.formatTen(d);
  },
  formatTen:function (num) {
    return num > 9 ? (num + "") : ("0" + num);
  },

4.获取近n天的日期(day= -7 近七天;day=0 当天)

  //获取近n天的日期(day=-7 近七天;day=0 当天)
  getDay:function (day) {
    let today = new Date();
    let targetDayStamp=today.getTime() + 1000*60*60*24*day;
    today.setTime(targetDayStamp); //注意,这行是关键代码
    let year = today.getFullYear();
    let month = today.getMonth();
    let date = today.getDate();
    return year+"-"+this.formatTen(month + 1)+"-"+this.formatTen(date);
  },
  formatTen:function (num) {
    return num > 9 ? (num + "") : ("0" + num);
  },

常见的日期格式

  1. 中国标准时间(newDate() 直接输出的就是这种格式):
    Sat May 23 2020 22:35:47 GMT+0800 (中国标准时间)
  2. UTC 协调世界时(后台偶尔会返回这类格式的数据接口)
    2020-02-22T09:12:43.083Z
  3. GMT-格林尼治标准时(new Date().toGMTString())
    Sat, 23 May 2020 14:41:34 GMT
  4. 时间戳(new Date().getTime())
    1590244981126
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值