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
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>
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>
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.