-8

How to convert the following date format Mon Apr 16 2018 19:00:00 GMT-0500 (Central Daylight Time) to 20180416190000 (YYYYMMDDHHMMSS)

Ajay Srikanth
  • 1,095
  • 4
  • 22
  • 43
  • 1
    Since you tagged the question [momentjs], you surely already looked at their documentation and tried something. Please post your code and tell us how it failed. – Bergi Apr 18 '18 at 19:53
  • 1
    what code have you written? – Daniel A. White Apr 18 '18 at 19:53
  • `let date = new Date('Mon Apr 16 2018 19:00:00 GMT-0500'); '' + date.getFullYear() + ...` – Jared Smith Apr 18 '18 at 19:54
  • @Bergi - The reason why I've put momentjs is that, we are using momentjs in our project, but upon looking at the documentation I didn't find any solution there. I mentioned that here, to see if anyone has a solution using momentjs. – Ajay Srikanth Apr 18 '18 at 19:58
  • 1
    "but upon looking at the documentation I didn't find any solution there" - you might want to look a little harder. This is pretty much moment's bread and butter. – rmlan Apr 18 '18 at 19:59
  • Ok thanks, I found the solution using momentjs. – Ajay Srikanth Apr 18 '18 at 20:07
  • Does this answer your question? [How to create date in YYYYMMDDHHMMSS format using javascript?](https://stackoverflow.com/questions/19448436/how-to-create-date-in-yyyymmddhhmmss-format-using-javascript) – tomByrer May 30 '21 at 22:11

2 Answers2

1

If you don't need to use moment.js you can use the toISOString() method returns a string in simplified extended ISO format (ISO 8601), which is always 24 or 27 characters long (YYYY-MM-DDTHH:mm:ss.sssZ or ±YYYYYY-MM-DDTHH:mm:ss.sssZ, respectively). The timezone is always zero UTC offset, as denoted by the suffix "Z".

Then after converting the date using the method, use the .replace() method and use regex to format the string then use the .slice() method.

const timeStamp = (new Date()).toISOString().replace(/[^0-9]/g, '').slice(0, -3)

console.log(timeStamp)

Output: 20210928063849

Philip Mutua
  • 6,016
  • 12
  • 41
  • 84
-1

To achieve expected result, use below option using moment.js format option

let date = new Date('Mon Apr 16 2018 19:00:00 GMT-0500');
console.log(moment(date).format('YYYYMMDDHHMMSS'))

codepen - https://codepen.io/nagasai/pen/ZoEwQB?editors=1010

Naga Sai A
  • 10,771
  • 1
  • 21
  • 40
  • console.log(moment(date).format('YYYYMMDDHHmmss')), we need to put mm in lowercase so we will get minutes value otherwise we will get the month. – avi Jul 21 '21 at 11:08