关于Date对象的拷问

454 阅读2分钟

判断两个date对象是否为同一周?

思路: 因为1970年1月1 是周4 所以(天数+4)/7 取整 就是周数 如果相同就是同一周反之就不是(以星期一作为每周的第一天)。

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

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);
        }
    });
};