Skip to content

Instantly share code, notes, and snippets.

@hungdev
Last active February 5, 2024 09:01
Show Gist options
  • Save hungdev/10e6f75866b02f9b3899ea0c213e33db to your computer and use it in GitHub Desktop.
Save hungdev/10e6f75866b02f9b3899ea0c213e33db to your computer and use it in GitHub Desktop.
dayjs different between 2 dates

docs: https://day.js.org/docs/en/plugin/duration

https://replit.com/@hungdev/dayjs-diff#index.js


const dayjs = require('dayjs');
require('dayjs/locale/vi'); // Import locale để có các chuỗi ngôn ngữ Việt Nam
var durationExt = require('dayjs/plugin/duration')
dayjs.extend(durationExt)

const start = dayjs('2024-02-01 12:30:00');
const end = dayjs('2024-02-01 13:45:30');

const diffInMilliseconds = end.diff(start);
const duration = dayjs.duration(diffInMilliseconds);

let result;

if (duration.days() > 0) {
    // Nếu khoảng cách lớn hơn 1 ngày
    result = duration.format('D [ngày] H [giờ] m [phút] s [giây]');
} else {
    // Nếu khoảng cách nhỏ hơn hoặc bằng 1 ngày
    result = duration.format('H [giờ] m [phút] s [giây]');
}

console.log(result);

https://stackoverflow.com/questions/72810167/get-minutes-and-hours-diff-with-dayjs/72810300#72810300

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment