Skip to content

Instantly share code, notes, and snippets.

@nielvid
Created July 27, 2023 14:48
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nielvid/764ec86c48eceaa21ee45b37b508eb7f to your computer and use it in GitHub Desktop.
Save nielvid/764ec86c48eceaa21ee45b37b508eb7f to your computer and use it in GitHub Desktop.
Get hour difference between two dated
export const getHoursDifference = (day1: string, day2: string) => {
const dayOne = new Date(day1).getTime();
const dayTwo = new Date(day2).getTime();
if (Number.isNaN(dayOne) || Number.isNaN(dayTwo)) {
throw new Error('invalid date or time format');
}
let hourDifference = (dayTwo - dayOne) / 1000;
hourDifference = hourDifference / (60 * 60);
return hourDifference;
};
//Format 12 hours time to 24 hours
export function formatDate(date: any, time: any) {
let day = date.split('T');
day = day[0];
const format = time.match(/[a-zA-Z]+/);
let formatedDate: string;
if (format) {
// ['pm', 'PM', 'am', 'AM'].includes(format[0]);
const hour = Number(time.match(/^(\d+)/)[1]);
const minute = time.match(/:(\d+)/)[1];
if (format[0] == 'pm' || format[0] == 'PM') {
if (hour < 12) {
formatedDate = `${day}T${hour + 12}:${minute}:00.000Z`;
}
}
if (format[0] == 'am' || format[0] == 'AM') {
if (hour < 12) {
if (hour < 10) {
formatedDate = `${day}T${'0' + hour}:${minute}:00.000Z`;
} else {
formatedDate = `${day}T${hour}:${minute}:00.000Z`;
}
}
if (hour == 12) {
formatedDate = `${day}T${hour - 12}:${minute}:00.000Z`;
}
}
return formatedDate!;
} else {
return `${day}T${time}:00.000Z`;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment