0

i have this date :

Mon Aug 23 2021 15:03:00 GMT+0430 (Iran Daylight Time)

how to convert this format:

2021-10-10T00:00:00

8
  • Is the first date hardcoded or received from JS ? Commented Aug 30, 2021 at 10:41
  • Can you explain the scenario of this conversion? Are you getting the data from database/ userinput? Commented Aug 30, 2021 at 10:46
  • I get it from the user(userinput) Commented Aug 30, 2021 at 10:47
  • date.getFullYear() + '-' + (date.getMonth() + 1) + '-' + date.getDate() + 'T00:00:00' developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/… Commented Aug 30, 2021 at 10:49
  • You can use moment.js : momentjs.com Commented Aug 30, 2021 at 10:51

1 Answer 1

2

You can do it as follows:

new Date('Mon Aug 23 2021 15:03:00 GMT+0430 (Iran Daylight Time)')
.toISOString().split('.')[0]

=> '2021-08-23T10:33:00'

If you don't prefer the native way of converting it you can use the library Moment.js.

Your code would look as follows:

moment('Mon Aug 23 2021 15:03:00 GMT+0430 (Iran Daylight Time)')
.format('YYYY-MM-DDTHH:mm:ss');

=> '2021-08-23T10:33:00'

If you don't want to keep the hours, minutes and seconds these examples will work.

Native way:

new Date('Mon Aug 23 2021 15:03:00 GMT+0430 (Iran Daylight Time)').toISOString().split('T')[0] + 'T00:00:00'

=> '2021-08-23T10:33:00'

With Moment.js:

moment('Mon Aug 23 2021 15:03:00 GMT+0430 (Iran Daylight Time)')
.format('YYYY-MM-DDT00:00:00');

=> '2021-08-23T10:33:00'

Edit

As RobG mentioned in the comments, the toISOString() function will return the UTC time format. So even one more reason to use moment.js!

Sign up to request clarification or add additional context in comments.

3 Comments

The "native way" returns UTC date and time masquerading as local, it is not a straight conversion of format.
The issue with toISOString isn't a reason to use a library, it's a reason not to use toISOString the way it's used here. ;-)
You can think of it in that way! Its just smarter to use moment.js because it offers more possibilities and flexability, but thank you for your input!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.