时间戳和本地时间间转换

时间戳转化本本地时间

系统标准时间转化为本地时间
let  initial = 'Fri Jan 10 2020 18:52:45 GMT+0800 (中国标准时间)' 		//中国标准时间
//定义一个时间转换函数
conversionTime :function(time){
        //转化为系统时间
        let date1 = new Date(time);
        //系统时间转化成时间戳
        let date2 = date1.getTime();
        
        const date = new Date(date2);
        const Y = date.getFullYear() + '-';
        const M = (date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1) + '-';
        const D = date.getDate() > 9 ? date.getDate() : '0' + date.getDate();
        // const h = date.getHours() + ':';
        // const m = date.getMinutes();
        // const s = date.getSeconds(); // 秒
        const dateString = Y + M + D ;
        // console.log('dateString', dateString); // > dateString 2020-01-10 18:52
        return dateString;
    }
时间戳转化成本地时间格式
const conversionTime = (time) => {
	//时间戳格式化
  const date = new Date(time);
  //时间戳转化为年
  const Y = date.getFullYear() + '-';
  //时间戳转化为月
  const M = (date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1) + '-';
  //时间戳转化为日
  const D = date.getDate() + ' ';
  //时间戳转化为时
  const h = date.getHours() + ':';
  //时间戳转化为分
  const m = date.getMinutes();
  //时间戳转化为秒
  const s = date.getSeconds(); 
  const time_new = Y + M + D + h + m + s;
  console.log('time_new', time_new); // > dateString 2020-01-10 18:52
  return time_new;
}
计算两个本地时间查 (天)
differenceTime :function(time1,time2){
        //转化为系统时间 、系统时间转化成时间戳
        let start_time = (new Date(time1)).getTime();
        let end_time = (new Date(time2)).getTime();
        //时间戳相减
        let diff_time = end_time - start_time;
        //重新格式化时间戳
        let date = new Date(diff_time);
        //时间戳换算成天
        let day = date/1000/60/60/24
        return day;
    },
获取当前本地时间
//获取当前日期
    getDate: function () {
	    const date = new Date();		//获取系统时间戳
	    let year = date.getFullYear();
	    let month = date.getMonth() + 1;
	    let day = date.getDate();
	    month = month > 9 ? month : '0' + month;;
	    day = day > 9 ? day : '0' + day;
	    return `${year}-${month}-${day}`;
	}

开发中经常用到的时间转换,在此记录与大家分享

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值