前端时间处理小结

前段时间的项目中接触了时间以及日期的处理,时间的格式化、时间戳,下面对这部分进行总结:

1.JS中,内置对象Date封装了时间处理方法。
回顾Date内置对象:

  • date.getFullYear() - 获取4位数年份
  • date.getMonth() - 获取月份,取值0~11,0对应1月份
  • date.getDay() - 获取星期,取值0~6,0对应星期天,1对应星期一,6对应星期六
  • date.getDate() - 获取一个月中的某天,取值1~31。1即1号,31即31号
  • date.getHours() - 获取小时数,取值0~23
  • date.getMinutes() - 获取分钟数,取值0~59
  • date.getSeconds() - 获取秒数,取值0~59
  • date.getMilliseconds() - 获取毫秒数,取值0~999
  • date.getTime() - 返回1970年1月1日至当前时间的毫秒数

另外要特别注意的是,new Date()创建时间对象时,参数最好是字符串格式,年月日之间用“/”,时分秒毫秒之间用“:”,如new Date(2017/7/25 12:12:12:100)
2.格式化时间格式-时间戳
//时间戳

function getLocalTime2(data) {
    var date = new Date(data);//时间戳为10位需*1000,时间戳为13位的话不需乘1000
    Y = date.getFullYear() + '-';
    M = (date.getMonth()+1 < 10 ? '0'+(date.getMonth()+1) : date.getMonth()+1) + '-';
    D = (date.getDate() + 1 < 10 ? '0' + (date.getDate() ) : date.getDate() ) + ' ';
    h = (date.getHours() +1< 10 ? '0' + (date.getHours()) : date.getHours() ) + ':';
    m = (date.getMinutes() +1< 10 ? '0' + (date.getMinutes()) : date.getMinutes()) + ':';
    s = date.getSeconds();
    return Y + M + D + h + m + s;
}

3.获取当前时间并后退30分钟,obj是前端传过来的30分钟。
按钮:

<p class="c-btn-xl c-btn-icon" value="0.5h" name="quick"
 onclick="quickEchart_bymin(30)" style="margin-left:10px;">最近半小时</p>

JS:

function quickEchart_byhour(obj){
    var timestamp = Date.parse(new Date());//获取当前时间     1567654262000  
    var nowtime1 = getLocalTime2(timestamp);//时间戳,格式化时间格式
    document.getElementById("endtime").value=nowtime1;
    var before = new Date(nowtime1);//获取结束时间 转变成Date格式
    var time2 = before.getTime() - 1000*60*obj;//getTime()获取当前毫秒数
    var starttime = getLocalTime2(time2);
    document.getElementById("starttime").value=starttime;
    quickEchart(starttime);
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值