Convert a Unix timestamp to time in JavaScript

前端 未结 29 2159
渐次进展
渐次进展 2020-11-21 04:57

I am storing time in a MySQL database as a Unix timestamp and that gets sent to some JavaScript code. How would I get just the time out of it?

For example, in HH/MM/

相关标签:
29条回答
  • 2020-11-21 05:33

    If you want to convert Unix time duration to real hours, minutes, and seconds, you could use the following code:

    var hours = Math.floor(timestamp / 60 / 60);
    var minutes = Math.floor((timestamp - hours * 60 * 60) / 60);
    var seconds = Math.floor(timestamp - hours * 60 * 60 - minutes * 60 );
    var duration = hours + ':' + minutes + ':' + seconds;
    
    0 讨论(0)
  • 2020-11-21 05:33

    Code below also provides 3-digit millisecs, ideal for console log prefixes:

    const timeStrGet = date => {
        const milliSecsStr = date.getMilliseconds().toString().padStart(3, '0') ;
        return `${date.toLocaleTimeString('it-US')}.${milliSecsStr}`;
    };
    
    setInterval(() => console.log(timeStrGet(new Date())), 299);

    0 讨论(0)
  • 2020-11-21 05:34

    The problem with the aforementioned solutions is, that if hour, minute or second, has only one digit (i.e. 0-9), the time would be wrong, e.g. it could be 2:3:9, but it should rather be 02:03:09.

    According to this page it seems to be a better solution to use Date's "toLocaleTimeString" method.

    0 讨论(0)
  • 2020-11-21 05:34

    This works with PHP timestamps

    var d = 1541415288860;
    //var d =val.timestamp;
    
    //NB: use + before variable name
    var date = new Date(+d);
    
    console.log(d);
    console.log(date.toDateString());
    console.log(date.getFullYear());
    console.log(date.getMinutes());
    console.log(date.getSeconds());
    console.log(date.getHours());
    console.log(date.toLocaleTimeString());

    var d =val.timestamp;
    var date=new Date(+d); //NB: use + before variable name
    
    console.log(d);
    console.log(date.toDateString());
    console.log(date.getFullYear());
    console.log(date.getMinutes());
    console.log(date.getSeconds());
    console.log(date.getHours());
    console.log(date.toLocaleTimeString());
    

    the methods above will generate this results

    1541415288860
    Mon Nov 05 2018 
    2018 
    54 
    48 
    13
    1:54:48 PM
    

    There's a bunch of methods that work perfectly with timestamps. Cant list them all

    0 讨论(0)
  • 2020-11-21 05:35

    Modern Solution (for 2020)

    In the new world, we should be moving towards the standard Intl JavaScript object, that has a handy DateTimeFormat constructor with .format() method:

    function format_time(s) {
      const dtFormat = new Intl.DateTimeFormat('en-GB', {
        timeStyle: 'medium',
        timeZone: 'UTC'
      });
      
      return dtFormat.format(new Date(s * 1e3));
    }
    
    console.log( format_time(12345) );  // "03:25:45"


    Eternal Solution

    But to be 100% compatible with all legacy JavaScript engines, here is the shortest one-liner solution to format seconds as hh:mm:ss:

    function format_time(s) {
      return new Date(s * 1e3).toISOString().slice(-13, -5);
    }
    
    console.log( format_time(12345) );  // "03:25:45"

    Method Date.prototype.toISOString() returns time in simplified extended ISO 8601 format, which is always 24 or 27 characters long (i.e. YYYY-MM-DDTHH:mm:ss.sssZ or ±YYYYYY-MM-DDTHH:mm:ss.sssZ respectively). The timezone is always zero UTC offset.

    This solution does not require any third-party libraries and is supported in all browsers and JavaScript engines.

    0 讨论(0)
  • 2020-11-21 05:36

    I'd think about using a library like momentjs.com, that makes this really simple:

    Based on a Unix timestamp:

    var timestamp = moment.unix(1293683278);
    console.log( timestamp.format("HH/mm/ss") );
    

    Based on a MySQL date string:

    var now = moment("2010-10-10 12:03:15");
    console.log( now.format("HH/mm/ss") );
    
    0 讨论(0)
提交回复
热议问题