Convert a Unix timestamp to time in JavaScript

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

    The modern solution that doesn't need a 40 KB library:

    Intl.DateTimeFormat is the non-culturally imperialistic way to format a date/time.

    // Setup once
    var options = {
        //weekday: 'long',
        //month: 'short',
        //year: 'numeric',
        //day: 'numeric',
        hour: 'numeric',
        minute: 'numeric',
        second: 'numeric'
    },
    intlDate = new Intl.DateTimeFormat( undefined, options );
    
    // Reusable formatter
    var timeStamp = 1412743273;
    console.log( intlDate.format( new Date( 1000 * timeStamp ) ) );
    
    0 讨论(0)
  • 2020-11-21 05:24

    Use:

    var s = new Date(1504095567183).toLocaleDateString("en-US")
    console.log(s)
    // expected output "8/30/2017"  
    

    and for time:

    var s = new Date(1504095567183).toLocaleTimeString("en-US")
    console.log(s)
    // expected output "3:19:27 PM"

    see Date.prototype.toLocaleDateString()

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

    shortest one-liner solution to format seconds as hh:mm:ss: variant:

    console.log(new Date(1549312452 * 1000).toISOString().slice(0, 19).replace('T', ' '));
    // "2019-02-04 20:34:12"

    0 讨论(0)
  • 2020-11-21 05:25
    function getTIMESTAMP() {
      var date = new Date();
      var year = date.getFullYear();
      var month = ("0" + (date.getMonth() + 1)).substr(-2);
      var day = ("0" + date.getDate()).substr(-2);
      var hour = ("0" + date.getHours()).substr(-2);
      var minutes = ("0" + date.getMinutes()).substr(-2);
      var seconds = ("0" + date.getSeconds()).substr(-2);
    
      return year + "-" + month + "-" + day + " " + hour + ":" + minutes + ":" + seconds;
    }
    
    //2016-01-14 02:40:01
    
    0 讨论(0)
  • 2020-11-21 05:28

    function timeConverter(UNIX_timestamp){
      var a = new Date(UNIX_timestamp * 1000);
      var months = ['Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec'];
      var year = a.getFullYear();
      var month = months[a.getMonth()];
      var date = a.getDate();
      var hour = a.getHours();
      var min = a.getMinutes();
      var sec = a.getSeconds();
      var time = date + ' ' + month + ' ' + year + ' ' + hour + ':' + min + ':' + sec ;
      return time;
    }
    console.log(timeConverter(0));

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

    JavaScript works in milliseconds, so you'll first have to convert the UNIX timestamp from seconds to milliseconds.

    var date = new Date(UNIX_Timestamp * 1000);
    // Manipulate JavaScript Date object here...
    
    0 讨论(0)
提交回复
热议问题