0

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?

Mārcis P
  • 316
  • 3
  • 10
  • 1
    Euh, don't you have the correct format already? 2020-05-13 13:49:50.000 ? Or what exactly is the problem? Turning that number back into a Date object? – Shilly Jun 30 '20 at 07:48
  • Yeah, parse it to date object – Mārcis P Jun 30 '20 at 07:57
  • Does this answer your question? [How to format a JavaScript date](https://stackoverflow.com/questions/3552461/how-to-format-a-javascript-date) – Paddy Jun 30 '20 at 08:55

3 Answers3

1

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 );
Shilly
  • 8,511
  • 1
  • 18
  • 24
  • The month can be just `month - 1`, the `-` operator coerces the string to number for you. ;-) – RobG Jun 30 '20 at 08:46
1

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());
RobG
  • 142,382
  • 31
  • 172
  • 209
0

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'))
Dhruv Shah
  • 1,611
  • 1
  • 8
  • 22