javascript 玩轉Date對象

前言:最近在作一個日期選擇功能,在日期轉換的時候常常換到暈,總結一下經常使用的Date對象的相關用法,方便往後直接查看使用~javascript

 

1. new Date()的使用方法有:java

    • 不接收任何參數:返回當前時間;
    • 接收一個參數x: 返回1970年1月1日 + x毫秒的值。
    • new Date(1, 1, 1)返回1901年2月1號。
    • new Date(2016, 1, 1)不會在1900年的基礎上加2016,而只是表示2016年2月1號。

 

2. 使用new Date(time) 將時間轉換成 Date 對象 api

注意:time格式須要爲 1999/12/31 23:59 (不能爲1999-12-30 23:43),不然在一些機型下可能會報錯。函數

 

3. date對象一些經常使用的apithis

new Date()轉換以後的數據,能夠直接使用下面的api
new Date(x).getMonth()+1   //獲取月份
new Date(x).getDate  //獲取日期
new Date(x).getHours()  //獲取小時
new Date(x).getMinutes()  //獲取分鐘
new Date(x).toLocaleDateString()); // 轉換爲本地日期格式,視環境而定,輸出:2017年07月04日
new Date(x).toLocaleString()); // 轉換爲本地日期和時間格式,視環境而定,輸出:2017年07月04日 上午10:03:05

 

4. javascript 沒有原生提供但卻常常需求使用的功能spa

  • 根據日期獲取當前星期幾
//參數  日期
getWeek(day) {
   const weekArr = ['星期日', '星期一', '星期二', '星期三', '星期四', '星期五', '星期六'];
   return weekArr[day];
}
getWeek(new Date(x).getDay()) 

 

  • 獲取某個時間+1個小時,直接對小時數進行加1可能會溢出,所以先轉換成 Date 對象,再使用setHours 改變小時。
new Date(x).setHours(new Date(x).getHours()+1,new Date(x).getMinutes());

 

  • 爲了統一格式,返回日期是10如下,需在前面補0.
function getFull(n) {
    return (n > 9 ? '' : '0') + n;
}
var x = getFull(3);  //03
var y = getFull(11);   //11

 

  • 常常要對日期進行轉換,所以增長一個轉換格式的函數
Date.prototype.Format = function (fmt) { //author: meizz
        var o = {
            "M+": this.getMonth() + 1, //月份
            "d+": this.getDate(), //
            "h+": this.getHours(), //小時
            "m+": this.getMinutes(), //
            "s+": this.getSeconds(), //
            "q+": Math.floor((this.getMonth() + 3) / 3), //季度
            "S": this.getMilliseconds() //毫秒
        };
        if (/(y+)/.test(fmt)) fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
        for (var k in o)
            if (new RegExp("(" + k + ")").test(fmt)) fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
        return fmt;
    }
    // 調用:
    var time1 = new Date().Format("yyyy-MM-dd");
    var time2 = new Date().Format("yyyy-MM-dd hh:mm:ss");
相關文章
相關標籤/搜索