Search code examples
javascriptdatedatetimetimecalendar

Convert Milliseconds to yyyy-MM-dd HH:mm:ss format Javascript


Input:-

milliSecond = '1519073776000';

Output:-

Date = "2018-02-20 02:26:16";

Convert Millisecond Date into yyyy-MM-dd HH:mm:ss format


Solution

  • There are two steps to your question.

    Step 1: Get date from milliseconds.

    This can easily be done by calling new Date(MILLISECONDS_AS_NUMBER);.

    Step 2: Format a date string from the Date object.

    This is a little more complicated, as there are no default method for doing this.

    The best method is to create a function that takes a format string and a date and simply stack format.replace(token, Date.key) calls.

    Here is an implementation of the above steps:

    function toDate(date) {
      if (date === void 0) {
        return new Date(0);
      }
      if (isDate(date)) {
        return date;
      } else {
        return new Date(parseFloat(date.toString()));
      }
    }
    
    function isDate(date) {
      return (date instanceof Date);
    }
    
    function format(date, format) {
      var d = toDate(date);
    
      return format
        .replace(/Y/gm, d.getFullYear().toString())
        .replace(/m/gm, ('0' + (d.getMonth() + 1)).substr(-2))
        .replace(/d/gm, ('0' + (d.getDate() + 1)).substr(-2))
        .replace(/H/gm, ('0' + (d.getHours() + 0)).substr(-2))
        .replace(/i/gm, ('0' + (d.getMinutes() + 0)).substr(-2))
        .replace(/s/gm, ('0' + (d.getSeconds() + 0)).substr(-2))
        .replace(/v/gm, ('0000' + (d.getMilliseconds() % 1000)).substr(-3));
    }
    //TEST
    var ms = '1519073776000';
    var dateFormat = "Y-m-d H:i:s.v";
    var formatted = format(ms, dateFormat);
    console.log(formatted);

    Alternatively you could opt-out of all this and use a library like MomentJS to handle this.