underscore like function that adds time to a date in typescript

index.ts
/**
 * Adds time to a date
 * @param date - the date to add time to
 * @param hours - the number of hours to add
 * @param minutes - the number of minutes to add
 * @param seconds - the number of seconds to add
 * @param milliseconds - the number of milliseconds to add
 * @returns - the new date with added time
 */
function addTimeToDate(date: Date, hours: number, minutes: number, seconds: number, milliseconds: number): Date {
  const newDate = new Date(date);

  newDate.setHours(newDate.getHours() + hours);
  newDate.setMinutes(newDate.getMinutes() + minutes);
  newDate.setSeconds(newDate.getSeconds() + seconds);
  newDate.setMilliseconds(newDate.getMilliseconds() + milliseconds);

  return newDate;
}
712 chars
20 lines

In the function addTimeToDate, we pass in a Date object and the number of hours, minutes, seconds, and milliseconds we want to add to it. We make a copy of the original date using new Date(date) and add each unit of time using the corresponding set method of the Date object. Finally, we return the new, modified Date object. This function can be used in TypeScript or vanilla JavaScript.

gistlibby LogSnag