简体   繁体   中英

Momentjs date value convert into datetime format

I have used moment js in date & time formatting, to be in a readable and string(month) manner. Now I am trying to get the same original formate here:

My original value: 2019-04-23T19:17:48.000Z

After moment: moment('2019-04-23T19:17:48.000Z').format('dddd Do YYYY, h:mm:ss')

output: Wednesday 24th 2019, 12:47:48

now all I need my original value back by using the output here.

Any lead appreciates for the answer.

With only the data you're providing as an output of Wednesday 24th 2019, 12:47:48 am you can't really get back to your original value. If it were a valid date, there's not a month. You'd need logic to determine what 24ths of each month in 2019 are a Wednesday.

After some testing - there's a few things you need in order to get this string back into a date that Moment can recognize

moment('2019-04-23T19:17:48.000Z').format('dddd MMMM D YYYY, h:mm:ss a')
moment('Tuesday April 23 2019, 7:17:48 pm').format()
  1. You have to have the month, otherwise it thinks its an invalid date. That can be the string of the month or just the number 4 in this case.
  2. Moment won't take the rd from 23rd otherwise it's an invalid date.

You can either use some string transformations to get it back into a useable date object or add on a little extra data like the month and when you go to use that date format,

"Tuesday April 23 2019, 7:17:48 pm".replace('April ', '')

Here are the best solution for the date formate under UTC/GMT:

let dateTime = new Date("2015-09-30T19:54:21.000Z");
dateTime = moment(dateTime).utc().format("YYYY-MM-DD HH:mm:ss");
moment(moment(dateTime).utc().format("YYYY-MM-DD HH:mm:ss")).format();

o/p => "2015-09-30T14:24:21+05:30"

moment("2015-09-30T14:24:21+05:30").format("YYYY-MM-DD HH:mm:ss")

o/p => "2015-09-30 14:24:21"

moment.tz('2015-09-30 14:24:21', 'YYYY-MM-DD HH:mm:ss', 'UTC').format()

final o/p => "2015-09-30T14:24:21Z"

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