0

i have a date like this which i should convert them into ISO format

const date = 05/23/2022;

i need like this

2022-05-23T00:00:00Z

Venkatesan M
  • 3
  • 1
  • 3
  • [toISOString](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toISOString) – Inder May 24 '22 at 06:19
  • Does this answer your question? [How do I output an ISO 8601 formatted string in JavaScript?](https://stackoverflow.com/questions/2573521/how-do-i-output-an-iso-8601-formatted-string-in-javascript) – ziishaned May 24 '22 at 06:19

2 Answers2

4

You can use String.split() to get the day, month and year for the Date in question.

We can then pass to the Date.UTC() function and then the Date() constructor. (Note: We pass monthIndex to the Date constructor, that's why we subtract 1 from the month )

To display as an ISO string, we can then use Date.toISOString()

const [month, day, year] = '05/23/2022'.split('/');
const date = new Date(Date.UTC(year, month - 1, day));
const result = date.toISOString();
console.log('Date (ISO):', result);

We can also do this easily with a Date / Time library such as luxon.

We'd use the DateTime.fromFormat() function to parse the input string, setting the timezone to 'UTC'.

To output the ISO date, we can use the DateTime.toISO() function:

const { DateTime } = luxon;
const date = DateTime.fromFormat('05/23/2022', 'MM/dd/yyyy', { zone: 'UTC'});
console.log('Date (ISO):', date.toISO())
<script src="https://cdnjs.cloudflare.com/ajax/libs/luxon/2.3.1/luxon.min.js" integrity="sha512-Nw0Abk+Ywwk5FzYTxtB70/xJRiCI0S2ORbXI3VBlFpKJ44LM6cW2WxIIolyKEOxOuMI90GIfXdlZRJepu7cczA==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>

We can also do this in moment.js, using moment.utc(), then .toISOString():

const date = moment.utc('05/23/2022', 'MM/DD/YYYY');
console.log('Date (ISO):', date.toISOString())
<script src="https://momentjs.com/downloads/moment.js"></script>
Terry Lennox
  • 29,471
  • 5
  • 28
  • 40
3

Note that .toISOString() always returns a timestamp in UTC, even if the moment in question is in local mode. This is done to provide consistency with the specification for native JavaScript Date .toISOString(), as outlined in the ES2015 specification.

let date = '24.05.2022 0:00:00';
let parsedDate = moment(date, 'DD.MM.YYYY H:mm:ss')
console.log(parsedDate.toISOString());
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.19.1/moment.min.js"></script>
scrummy
  • 795
  • 1
  • 6
  • 20