简体   繁体   中英

What format timestamp is this in PHP and why can't i convert it using javascript?

This API i am using returns a timestamp in the format below. It is only explained as "timestamp in UTC" in their docs. I can not figure out what format this is, or how to convert it using javascript. I have tried using new Date(), moment.js, and everything in-between. Can anyone explain how to do this in JS instead of PHP?

// timestamp from api
20200430094700

using Javascript, i always get something way off like:

Friday, February 16, 2610 6:34:54.700 AM

Here i will use PHP to convert it to a correct unix timestamp and a date object

$timestamp = 20200430094700;

$e = new DateTime($timestamp);

// This is the correct Unix timestamp
// 1588258020
echo date_timestamp_get($e);        

// This is the correct date
// [date] => 2020-04-30 09:47:00.000000
print_r($e);

As has been pointed out in the comments, 20200430094700 is not a timestamp but a date in the format YYYYMMDDHHMMSS . To convert that into a Date in JavaScript, you need to extract the component parts (using eg .slice ), subtract one from the month to make it a JS month (indexed from 0) and then pass that into Date.UTC and use its output in the Date constructor:

 const ts = '20200430094700'; const d = new Date(Date.UTC(ts.slice(0,4), ts.slice(4,6)-1, ts.slice(6,8), ts.slice(8,10), ts.slice(10,12), ts.slice(12,14))); console.log(d);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM