javascriptdayjs

How to combine date and time using dayjs?


If following data represent date and time respectively:

date: 2023-04-04
time: 13:02:00.963+00:00

How do I combine above date and time using dayjs, so it looks as below format:

2023-04-04T13:02:00.963Z

Is there any built-in method to do this? and what're the alternatives?

Thank you


Solution

  • you can use the inbuilt Date.toISOString for this in case you are wondering

    const date = '2023-04-04'
    const time = '13:02:00.963+00:00'
    
    const datetime = new Date(`${date}T${time}`).toISOString()
    
    console.log(datetime)

    or using dayjs

    const date = '2023-04-04'
    const time = '13:02:00.963+00:00'
    
    const datetime = dayjs(`${date}T${time}`).toISOString()
    
    console.log(datetime)
    <script src="https://cdnjs.cloudflare.com/ajax/libs/dayjs/1.11.7/dayjs.min.js"></script>

    or using moment

    const date = '2023-04-04'
    const time = '13:02:00.963+00:00'
    
    const datetime = moment(`${date}T${time}`).toISOString()
    
    console.log(datetime)
    <script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.29.4/moment.min.js"></script>

    or using luxon

    const DateTime = luxon.DateTime
    
    const date = '2023-04-04'
    const time = '13:02:00.963+00:00'
    
    const datetime = DateTime.fromISO(`${date}T${time}`, { setZone: true }).toISO()
    console.log(datetime)
    <script src="https://cdnjs.cloudflare.com/ajax/libs/luxon/3.3.0/luxon.min.js"></script>