Date对象

    Date对象,以前每次看书都没有重视过,每次要用的时候就去查相应的函数,api不熟悉。虽然可能失败了,但是知道自己哪里不行,能学到东西就已经很开心了,而且还涨了个教训,挺好的。下面来看看api得到的具体结果是什么。

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    var now = new Date();
    console.log(now);
    console.log(now.toLocaleString());
    console.log(now.toGMTString());
    console.log(now.getUTCDate());
    console.log(now.getTime());
    console.log(now.valueOf());
    console.log(Date.parse(now));
    console.log(now.getDate());
    console.log(now.getDay());
    console.log(now.getHours());
    console.log(now.getFullYear());
    console.log(now.toString());
    var dt = new Date("2012-12-1");
    console.log(dt);

    date

    判断时间就用时间戳是最方便的,把每个时间戳都算出来。然后对比是不是在相应的时间段内。当时写的时候,不能在本机调试,所以不知道每个调用函数得到的结果是什么。还是要多写多练才好,这样熟了,也不用一个个去打印调试了。加油。

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    //获取某年某月某天的0点的时间戳
    function setDate0(dateTime){
    var year = dateTime.getFullYear();
    var month = dateTime.getMonth();
    var day = dateTime.getDate();
    var newDate = new Date(year,month,day,0,0,0);
    return newDate.getTime();
    }
    function printTime(datetime){
    //设置一天的微秒数
    var micro = 24*60*60*1000;
    //获取dateTime对应的时间对象,datetime为时间戳,大小写区分
    var dateTime = new Date(datetime);
    //获取今天此刻的时间戳和时间
    var today = new Date();
    var todayTS = today.getTime();
    //获取今天0点的时间戳
    var today0 = setDate0(today);
    //明天的0点时间戳
    var tom0 = today0 + micro;
    //获取昨天零点的时间戳
    var yesterday0 = today0 - micro;
    //获取一个本星期一开头的时间戳
    var week0 = today0 - ((today.getDay()+6)%7)*micro;
    console.log(today0+"hello"+tom0+"world"+week0);
    //开始判断和输出
    if(datetime >= today0 && datetime < tom0){
    return dateTime.getHours()+":"+dateTime.getMinutes();
    }else if(datetime >= yesterday0 && datetime < today0){
    return "昨天";
    }else if(datetime >= week0 && datetime < yesterday0){
    var arr = ["周日","周一","周二","周三","周四","周五","周六"];
    return arr[dateTime.getDay()];
    }else{
    return null;
    }
    }
    console.log(printTime(1458803593715));