Convert a Unix timestamp to time in JavaScript

前端 未结 29 2088
渐次进展
渐次进展 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: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.

提交回复
热议问题