简体   繁体   中英

How can I get the ISO format for date and time in javascript?

I have two separate fields of date and time:-

const date = 2020-12-10;
const time = 22:00;

expected output:-

2020-12-10T10:00:00Z

I'm following this approach but the time in coming wrong:-

const date = DateUtil.getFullDateString(this.state.date_value);
const time = moment(this.state.time_value, ['HH.mm']).format('hh:mm a');
const momentObj = moment(date + time, 'YYYY-MM-DD HH:mm');
const dateTime = momentObj.toISOString();

the output of time is coming 18:30:00 but need to have 10:00:00

2020-12-10T18:30:00Z

You could parse date and time one by one, then add time to date and finally format as you want.

 const date = '2020-12-10'; const time = '22:00'; const momentDate = moment(date).utc().startOf('day'); // utc() to avoid the offset console.log(momentDate); const momentTime = moment(time, 'HHmm').format('HH:mm'); console.log(momentTime); const resultTime = momentDate.add(momentTime); console.log(resultTime); // Format as you want console.log(resultTime.format('LLL')); console.log(resultTime.format('YYYY-MM-DDThh:mm:ss.SSSA[Z]')); console.log(resultTime.toISOString());
 <script src="https://momentjs.com/downloads/moment.js"></script>

See this in order to know how to manage the UTC offset.

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