[removed] get month/year/day from unix timestamp

后端 未结 3 1943
半阙折子戏
半阙折子戏 2021-01-01 20:19

I have a unix timestamp, e.g., 1313564400000.00. How do I convert it into Date object and get month/year/day accordingly? The following won\'t work:

function         


        
相关标签:
3条回答
  • 2021-01-01 20:24

    Instead of using parse, which is used to convert a date string to a Date, just pass it into the Date constructor:

    var date = new Date(timestamp);
    

    Make sure your timestamp is a Number, of course.

    0 讨论(0)
  • 2021-01-01 20:32

    An old question, but none of the answers seemed complete, and an update for 2020:

    For example: (you may have a decimal if using microsecond precision, e.g. performance.now())

    let timestamp = 1586438912345.67;
    

    And we have:

    var date = new Date(timestamp); // Thu Apr 09 2020 14:28:32 GMT+0100 (British Summer Time)
    let year = date.getFullYear(); // 2020
    let month = date.getMonth() + 1; // 4 (note zero index: Jan = 0, Dec = 11)
    let day = date.getDate(); // 9
    

    And if you'd like the month and day to always be a two-digit string (e.g. "01"):

    let month = (date.getMonth() + 1).toString().padStart(2, '0'); // "04"
    let day = date.getDate().toString().padStart(2, '0'); // "09"
    

    For extended completeness:

    let hour = date.getHours(); // 14
    let minute = date.getMinutes(); // 28
    let second = date.getSeconds(); // 32
    let millisecond = date.getMilliseconds(); // 345
    let epoch = date.getTime(); // 1586438912345 (Milliseconds since Epoch time)
    

    Further, if your timestamp is actually a string to start (maybe from a JSON object, for example):

    var date = new Date(parseFloat(timestamp));
    

    More info if you want it here (2017).

    0 讨论(0)
  • 2021-01-01 20:38
    var date = new Date(1313564400000);
    var month = date.getMonth();
    

    etc.

    This will be in the user's browser's local time.

    0 讨论(0)
提交回复
热议问题