How do you get a timestamp in JavaScript?

前端 未结 30 3539
情深已故
情深已故 2020-11-21 15:19

How can I get a timestamp in JavaScript?

Something similar to Unix timestamp, that is, a single number that represents the current time and date. Either as a number

30条回答
  •  刺人心
    刺人心 (楼主)
    2020-11-21 15:52

    This seems to work.

    console.log(clock.now);
    // returns 1444356078076
    
    console.log(clock.format(clock.now));
    //returns 10/8/2015 21:02:16
    
    console.log(clock.format(clock.now + clock.add(10, 'minutes'))); 
    //returns 10/8/2015 21:08:18
    
    var clock = {
        now:Date.now(),
        add:function (qty, units) {
                switch(units.toLowerCase()) {
                    case 'weeks'   :  val = qty * 1000 * 60 * 60 * 24 * 7;  break;
                    case 'days'    :  val = qty * 1000 * 60 * 60 * 24;  break;
                    case 'hours'   :  val = qty * 1000 * 60 * 60;  break;
                    case 'minutes' :  val = qty * 1000 * 60;  break;
                    case 'seconds' :  val = qty * 1000;  break;
                    default       :  val = undefined;  break;
                    }
                return val;
                },
        format:function (timestamp){
                var date = new Date(timestamp);
                var year = date.getFullYear();
                var month = date.getMonth() + 1;
                var day = date.getDate();
                var hours = date.getHours();
                var minutes = "0" + date.getMinutes();
                var seconds = "0" + date.getSeconds();
                // Will display time in xx/xx/xxxx 00:00:00 format
                return formattedTime = month + '/' + 
                                    day + '/' + 
                                    year + ' ' + 
                                    hours + ':' + 
                                    minutes.substr(-2) + 
                                    ':' + seconds.substr(-2);
                }
    };
    

提交回复
热议问题