Skip to content

Instantly share code, notes, and snippets.

@gladchinda
Last active June 2, 2022 08:43
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save gladchinda/91f282e50852b2a77cb25224099f30e3 to your computer and use it in GitHub Desktop.
Save gladchinda/91f282e50852b2a77cb25224099f30e3 to your computer and use it in GitHub Desktop.
Get human readable time string for an hour from current time (with optional offset).
const oneHourFromNow = (() => {
const pad = num => `0${num}`.slice(-2);
const parse = num => Math.max(~~parseFloat(num), 0);
const meridian = hour => ["AM", "PM"][+(hour >= 12)];
const tomorrow = date => date.getDate() > new Date().getDate();
const timezone = date => `GMT+${-(date.getTimezoneOffset() / 60)}`
// .replace(/\+?([-+])/, "$1");
.replace(/\+?([-+])(\d+)/, (_, $1, $2) => +$2 ? `${$1}${$2}` : "");
return (offset) => {
const date = new Date(Date.now() + (3600 - parse(offset)) * 1000);
const minute = date.getMinutes();
const hour = date.getHours();
return `${tomorrow(date) ? "tomorrow" : "today"} by ${[
pad(hour > 12 ? hour % 12 : hour),
pad(minute)
].join(":")} ${meridian(hour)} (${timezone(date)})`;
};
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment