Home > Software engineering >  Dayjs difference between two date time has a default of 8hours
Dayjs difference between two date time has a default of 8hours

Time:01-21

I am confused why the difference between these two dates has a default of 8 hours? I am expecting a result something like 00:12:32 at least in my case from the time I posted this. Right now, in the result, the hour has a default of 8.

const date1 = dayjs(Date.now())
const date2 = dayjs(1674235010388)

// Check date date1
console.log('date1 =', dayjs(date1).format('hh:mm:ss'))

// Check date2 date
console.log('date2 =', dayjs(date2).format('hh:mm:ss'))

const result = date1.diff(date2)
console.log(dayjs(result).format('hh:mm:ss'))
<script src="https://cdn.jsdelivr.net/npm/dayjs@1/dayjs.min.js"></script>

CodePudding user response:

I cannot tell you but it is another reason for not using these frameworks when plain JS is more predictible

const ms2hhmmss = ms => new Date(ms).toISOString().slice(11,19); // grab the time from YYYY-MM-DDTHH:MM:SS.milZ

const date1 = new Date()
const date2 = new Date(1674235010388)
console.log(date1)
console.log(date2)

const diff = Math.abs(date1 - date2)
console.log(ms2hhmmss(diff))

CodePudding user response:

Here's how to do it with dayjs and the duration plugin, in case anyone comes here looking for that answer. For some reason I had to make the loading of the duration plugin async and wire it up manually. I expect it has something to do with a) Stack Snippets and b) the lack of caffeine in my brain.

@mplungjan is correct, of course, it's quite simple without dayjs as well.

document.querySelector('#duration').onload = (e) => {
  dayjs.extend(dayjs_plugin_duration);

  const date1 = dayjs(Date.now())
  const date2 = dayjs(1674235010388)
  // Check date date1
  console.log('date1 =', date1.format('YYYY-MM-DD hh:mm:ss'))

  // Check date2 date
  console.log('date2 =', date2.format('YYYY-MM-DD hh:mm:ss'))

  const result = dayjs.duration(date1.diff(date2));
  console.log(result.format('HH:mm:ss'))
};
<script src="https://cdnjs.cloudflare.com/ajax/libs/dayjs/1.11.7/dayjs.min.js" integrity="sha512-hcV6DX35BKgiTiWYrJgPbu3FxS6CsCjKgmrsPRpUPkXWbvPiKxvSVSdhWX0yXcPctOI2FJ4WP6N1zH 17B/sAA==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/dayjs/1.11.7/plugin/duration.min.js" integrity="sha512-QxVJ3lAILV0RSq3wPNV5CFNyyywxd5QfA9jfGfzVViwpL/eWSi5dR1nZMc02c QE4xz2L1eQvx/fn18RrUq9lw==" crossorigin="anonymous" referrerpolicy="no-referrer" id="duration" async></script>

  • Related