Reputation: 326
I have a 'timestamp' value 20200513134950000
and the format should be YYYYMMDDmmhhssuuu.
I can not wrap my head around how to properly format it. I have tried date-fns library and native Date format, but with no luck.
Any ideas?
Upvotes: 0
Views: 235
Reputation: 147403
Without any library you can just get the parts and pass them to the Date constructor:
let ts = '20200513134950000';
let [c,y,m,d,H,M,S] = ts.match(/\d\d/g);
console.log(new Date(c+y,--m,d,H,M,S).toString());
Upvotes: 1
Reputation: 8589
You can extract all the relevant parts from the number with a simple regexp or even by counting numbers. Then the only caveat is that months are zero-based, but apart from that, you can just use the standard Date() constructor.
const timestamp = 20200513134950000;
const UTC_mask = /(\d{4})(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})(\d{3})/;
const [
year,
month,
day,
hour,
min,
sec,
ms
] = timestamp.toString().match( UTC_mask ).slice( 1 );
const datetime = new Date( year, parseInt( month, 10 ) - 1, day, hour, min, sec, ms );
console.log( datetime );
Upvotes: 1
Reputation: 1651
You can try using DayJS.
Its a lightweight library and allows you to specify custom parse format
for parsing the dates.
const dayjs = require('dayjs');
var customParseFormat = require('dayjs/plugin/customParseFormat')
dayjs.extend(customParseFormat)
console.log(dayjs('20200513134950000', 'YYYYMMDDmmhhssuuu'))
Upvotes: 0