-1

I have a problem converting new Date() to timestamp in ES6. Timestamp should look like this 10012020120012.

10/01/2020 12:00:12AM should be 10012020120012

here is my code below:

let myDate = new Date().toLocaleString('en-US', {
    month: '2-digit',
    day: '2-digit',
    year: 'numeric',
  });
 myDate = myDate.split('-');
 let newDate = new Date(myDate[2], myDate[1] - 1, myDate[0]);

console.log(newDate.getTime())
Joseph
  • 7,042
  • 23
  • 83
  • 181
  • Are you trying to get [`MMddYYYYHHmm`](https://stackoverflow.com/questions/3552461/how-to-format-a-javascript-date) or a [Unix timestamp](https://stackoverflow.com/questions/221294/how-do-you-get-a-timestamp-in-javascript)? – VLAZ Oct 01 '20 at 05:35
  • @VLAZ. `10/01/2020 12:00:12AM` should be `10012020120012` – Joseph Oct 01 '20 at 05:38
  • Then why create the date, then make it into another date object to get the Unix timestamp of it? Check the first link for how to format dates. For convenience you can also use a date library like date-fns, for example. – VLAZ Oct 01 '20 at 05:39
  • @VLAZ. ok date-fns is fine. How would i convert that to timestamp using date-fns – Joseph Oct 01 '20 at 05:40
  • `dateFns.format(new Date('2020-10-01'), 'MMDDYYYYHHmm');` – VLAZ Oct 01 '20 at 05:47
  • Could you please check my answer again – errorau Oct 01 '20 at 06:51
  • @VLAZ. Thanks but could you do it without package? – Joseph Oct 01 '20 at 07:51
  • @Joseph again - check the first link in my first comment. – VLAZ Oct 01 '20 at 07:52
  • @VLAZ. I can;t see anything related to what i want, `10012020120012`. Could you put the code here? Thank you – Joseph Oct 01 '20 at 07:56
  • @Joseph [see this answer](https://stackoverflow.com/a/30272803/) - you can just use `getMonth()`, `getDate()`, `getYear()`, `getHours()`, `getMinutes()`, `getSeconds()`. – VLAZ Oct 01 '20 at 07:58

1 Answers1

-1

Try this, it works in my console. Split by '/' instead of '-'

let myDate = new Date().toLocaleString('en-US', {
  month: '2-digit',
  day: '2-digit',
  year: 'numeric',
});
myDate = myDate.split('/');
let newDate = new Date(myDate[2], myDate[1] - 1, myDate[0]);

console.log(newDate.getTime())
Fullstack Guy
  • 16,368
  • 3
  • 29
  • 44
Ali Raza
  • 174
  • 1
  • 2
  • 8