-
Notifications
You must be signed in to change notification settings - Fork 28
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
utlis: add function to diff timestamps
- Loading branch information
1 parent
e3306a6
commit de12d20
Showing
2 changed files
with
56 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,55 @@ | ||
// This file is part of React-Invenio-Forms | ||
// Copyright (C) 2024 CERN. | ||
// | ||
// React-Invenio-Forms is free software; you can redistribute it and/or modify it | ||
// under the terms of the MIT License; see LICENSE file for more details. | ||
|
||
import { DateTime } from "luxon"; | ||
|
||
/** | ||
* Create duration string for two given timestamps | ||
* | ||
* @param firstTimestamp string ISO timestamp | ||
* @param secondTimestamp string ISO timestamp | ||
* @returns {string} string representation of duration, i.e. 3 days | ||
*/ | ||
export const diffTimestamps = (firstTimestamp, secondTimestamp, language = "en") => { | ||
const first = DateTime.fromISO(firstTimestamp); | ||
const second = DateTime.fromISO(secondTimestamp); | ||
const duration = first.diff(second).reconfigure({ locale: language }); | ||
// If we used a newer version of luxon we could just do this: | ||
// return duration.toHuman(); | ||
|
||
// instead return the largest unit and value (ignore everything smaller) | ||
const rescale = duration.shiftTo( | ||
"years", | ||
"months", | ||
"weeks", | ||
"days", | ||
"hours", | ||
"minutes", | ||
"seconds", | ||
"milliseconds" | ||
); // in new luxon this is just duration.rescale() | ||
const units = [ | ||
"years", | ||
"months", | ||
"weeks", | ||
"days", | ||
"hours", | ||
"minutes", | ||
"seconds", | ||
"milliseconds", | ||
]; | ||
|
||
for (const unit of units) { | ||
if (rescale[unit] && rescale[unit] > 0) { | ||
if (rescale[unit] == 1) { | ||
Check warning on line 47 in src/lib/locale/DiffTimestamps.js GitHub Actions / Tests (18.x)
|
||
return rescale[unit] + " " + unit.slice(0, -1); // remove s | ||
} else { | ||
return rescale[unit] + " " + unit; | ||
} | ||
} | ||
} | ||
return "-"; // in case all components are zero | ||
}; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1 +1,2 @@ | ||
export { toRelativeTime } from "./RelativeTime"; | ||
export { diffTimestamps } from "./DiffTimestamps"; |