3

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

Mir Stephen
  • 1,758
  • 4
  • 23
  • 54

2 Answers2

2

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>
cmgchess
  • 7,996
  • 37
  • 44
  • 62
0

To combine a date and time using Day.js, you can use the .set() method to set the time part of the date to the desired time value. Here is an example:

const dayjs = require('dayjs');

// create a date object with a specific date
const date = dayjs('2023-04-23');

// create a time object with a specific time
const time = dayjs('10:30:00', 'HH:mm:ss');

// combine the date and time objects
const dateTime = date.set('hour', time.hour()).set('minute', time.minute()).set('second', time.second());

console.log(dateTime.format('YYYY-MM-DD HH:mm:ss')); // Output: 2023-04-23 10:30:00
Doesystem
  • 61
  • 1
  • 4