简体   繁体   中英

Format Luxon date to ISO8601 basic format

I'm using Luxon to format a DateTime, and I need to it to be the following format, including the 'T' and 'Z' characters:

20150830T123600Z

I've tried to format the DateTime using:

let dateTimeNow = DateTime.now();
let formattedDateTime = dateTimeNow.toFormat('yyyyMMddTHHmmssZ');

But I get the format:

2021-05-25T12:43:37.043Z 

How do I remove the '-', ':' and '.' symbols?

You may escape strings using single quotes (Doc: Escaping ), so you can use toFormat("yyyyMMdd'T'HHmmss'Z'") .

Please note that the Z at the ends stands for UTC+0 offset, so I suggest to do not use it to represent local times with different offset.

Example:

 const DateTime = luxon.DateTime; let dateTimeNow = DateTime.utc(); let formattedDateTime = dateTimeNow.toFormat("yyyyMMdd'T'HHmmss'Z'"); console.log(formattedDateTime)
 <script src="https://cdn.jsdelivr.net/npm/luxon@1.26.0/build/global/luxon.js"></script>

Instead of composing the format, you can also use basic ISO format:

 const DateTime = luxon.DateTime; let dateTimeNow = DateTime.now().toUTC().startOf('second'); console.log(dateTimeNow.toISO({ format: 'basic', suppressMilliseconds: true }))
 <script src="https://cdn.jsdelivr.net/npm/luxon@2.2.0/build/global/luxon.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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM