本文轉載自:關於Date對象

本文轉載自:
關於Date對象
https://juejin.im/post/5e5f5011e51d4527151566b0
判斷兩個date對象是否爲同一周?
思路: 因爲1970年1月1 是周4 所以(天數+4)/7 取整 就是週數 如果相同就是同一周反之就不是(以星期一作爲每週的第一天)。

function isSameWeek(old,now){
     var oneDayTime = 1000*60*60*24;  
     var old_count =parseInt(old.getTime()/oneDayTime);  
     var now_other =parseInt(now.getTime()/oneDayTime);  
     return parseInt((old_count+4)/7) == parseInt((now_other+4)/7);  
 } 

Date的構造函數接受哪幾種形式的參數?

var today = new Date();
var today = new Date(1453094034000); // by timestamp(accurate to the millimeter)
var birthday = new Date('December 17, 1995 03:24:00');
var birthday = new Date('1995-12-17T03:24:00');
var birthday = new Date(1995, 11, 17);
var birthday = new Date(1995, 11, 17, 3, 24, 0);
var unixTimestamp = Date.now(); // in milliseconds

需要注意的是在Safari和Chrome中,對於dateString的構造方式還是有些不同的,
如下面這個時間字符串在Chrome中是可以解析的,而在Safari中將拋出異常。
new Date('2017-10-14 08:00:00')
//在Chrome中正常工作,而Safari中拋出異常Invalid Date

new Date('2017/10/14 08:00:00');
new Date('2017-10-14');
//上面這兩種構造方式都在兩個瀏覽器都是可以正常運行的,說明Chrome的檢查範圍更寬泛

如何將Date對象輸出爲指定格式的字符串,如(new Date(), 'YYYY.MM.DD') => '2020.03.04'
思路就是將預先想定的格式字符串通過replace方法替換成對應的時間片段,如將YYYY替換成Date.prototype.getFullYears()
的輸出,當然每種形式還有不同的替換規則,但是思路大致相同。

function formatDate(date, format) {
    if (arguments.length < 2 && !date.getTime) {
        format = date;
        date = new Date();
    }
    typeof format != 'string' && (format = 'YYYY年MM月DD日 hh時mm分ss秒');
    var week = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', '日', '一', '二', '三', '四', '五', '六'];
    return format.replace(/YYYY|YY|MM|DD|hh|mm|ss|星期|周|www|week/g, function(a) {
        switch (a) {
            case "YYYY": return date.getFullYear();
            case "YY": return (date.getFullYear()+"").slice(2);
            case "MM": return (date.getMonth() + 1 < 10) ? "0"+ (date.getMonth() + 1) : date.getMonth() + 1;
            case "DD": return (date.getDate() < 10) ? "0"+ date.getDate() : date.getDate();
            case "hh": return (date.getHours() < 10) ? "0"+ date.getHours() : date.getHours();
            case "mm": return (date.getMinutes() < 10) ? "0"+ date.getMinutes() : date.getMinutes();
            case "ss": return (date.getSeconds() < 10) ? "0"+ date.getSeconds() : date.getSeconds();
            case "星期": return "星期" + week[date.getDay() + 7];
            case "周": return "周" +  week[date.getDay() + 7];
            case "week": return week[date.getDay()];
            case "www": return week[date.getDay()].slice(0,3);
        }
    });
};
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章