Convert 17-digit precision unix time (UTC) to date fromat In javascript

后端 未结 3 1589
猫巷女王i
猫巷女王i 2021-01-20 20:35

I got time token like this from 14512768065185892 from PubNub.I need to convert this time token into following format dd/mm/yy.

Any one ple

3条回答
  •  春和景丽
    2021-01-20 20:55

    PubNub times have an extra 7 digits of precision above standard UNIX time stamps (seconds) so the first step is to divide it by 107. That gives you 1451276806 which, when you test it in a converter, you get 12/28/2015 @ 4:26am (UTC) (using the frankly bizarre(1) US date format) so it seems to be reasonable.

    In terms of using Javascript to do this, you can pass the number of milliseconds to Date to have an object instantiated for you:

    var dtobj = new Date(1451276806518);
    

    keeping in mind that the millisecond value entails you dividing by 104 (lopping off the final four digits) rather than 107.

    Once you have the date object, you can use standard methods to get it in the format you want, such as:

    var dtobj = new Date(1451276806518);
    var dtdd = ('0' + (dtobj.getDate())).slice(-2);
    var dtmm = ('0' + (dtobj.getMonth() + 1)).slice(-2);
    var dtyy = ('0' + (getFullYear() % 100)).slice(-2);
    
    document.write(dtdd + "/" + dtmm + "/" + dtyy);
    

    (1) I swear some committee must have taken the worst bits from all date formats to indicate what needed to be discarded, then some other committee accidentally took that as a recommendation. Needless to say, I'm a big fan of ISO 8601 :-)

提交回复
热议问题