Skip to content

Instantly share code, notes, and snippets.

@JPBM135
Created December 12, 2024 05:53
Show Gist options
  • Save JPBM135/aa0ac9ff76ddad3b75a5b034a22f13af to your computer and use it in GitHub Desktop.
Save JPBM135/aa0ac9ff76ddad3b75a5b034a22f13af to your computer and use it in GitHub Desktop.
TimeSpan for time conversion and operations

TimeSpan Utility Class

The TimeSpan class is a utility for managing and manipulating time intervals in TypeScript/JavaScript. It provides a simple, object-oriented way to perform arithmetic and comparison operations on time spans. This class can be used to represent durations in milliseconds, seconds, minutes, hours, or days.

Features

  • Creation Methods: Create TimeSpan objects from various inputs (current time, Date objects, milliseconds, seconds, minutes, hours, or days).
  • Conversion Methods: Convert a TimeSpan to milliseconds, seconds, minutes, hours, or days.
  • Arithmetic Operations: Add, subtract, multiply, and divide TimeSpan objects.
  • Comparison Methods: Compare TimeSpan objects using equality, less than, greater than, etc.
  • Time Checks: Check if the TimeSpan represents a past or future time.

Installation

To use the TimeSpan utility, import it into your TypeScript or JavaScript project.

import { TimeSpan } from './TimeSpan';

Usage

Creating a TimeSpan

const spanFromNow = TimeSpan.fromNow(); // From the current time
const spanFromDate = TimeSpan.fromDate(new Date()); // From a Date object
const spanFromMilliseconds = TimeSpan.fromMilliseconds(5000); // From milliseconds
const spanFromSeconds = TimeSpan.fromSeconds(5); // From seconds
const spanFromMinutes = TimeSpan.fromMinutes(2); // From minutes
const spanFromHours = TimeSpan.fromHours(1); // From hours
const spanFromDays = TimeSpan.fromDays(1); // From days

Getting Total Time Units

const span = TimeSpan.fromMilliseconds(90061);

console.log(span.milliseconds()); // 90061
console.log(span.seconds()); // 90 (rounded)
console.log(span.minutes()); // 1 (rounded)
console.log(span.hours()); // 0 (rounded)
console.log(span.days()); // 0 (rounded)

Arithmetic Operations

const span1 = TimeSpan.fromSeconds(30);
const span2 = TimeSpan.fromSeconds(45);

const sum = span1.add(span2); // Adds two TimeSpans
const difference = span2.subtract(span1); // Subtracts two TimeSpans
const product = span1.multiply(2); // Multiplies a TimeSpan by a factor
const quotient = span2.divide(2); // Divides a TimeSpan by a divisor

Comparison Methods

const span1 = TimeSpan.fromSeconds(30);
const span2 = TimeSpan.fromSeconds(45);

console.log(span1.equals(span2)); // false
console.log(span1.lessThan(span2)); // true
console.log(span1.lessThanOrEqual(span2)); // true
console.log(span2.greaterThan(span1)); // true
console.log(span2.greaterThanOrEqual(span1)); // true

Time Checks

const futureTimeSpan = TimeSpan.fromMilliseconds(Date.now() + 10000);
const pastTimeSpan = TimeSpan.fromMilliseconds(Date.now() - 10000);

console.log(futureTimeSpan.isFuture()); // true
console.log(pastTimeSpan.isPast()); // true

Converting to String

const span = TimeSpan.fromMilliseconds(123456);
console.log(span.toString()); // '123456'

API Reference

Static Methods

  • TimeSpan.fromNow(): TimeSpan — Creates a TimeSpan from the current time.
  • TimeSpan.fromDate(date: Date): TimeSpan — Creates a TimeSpan from a Date object.
  • TimeSpan.fromMilliseconds(milliseconds: number): TimeSpan — Creates a TimeSpan from milliseconds.
  • TimeSpan.fromSeconds(seconds: number): TimeSpan — Creates a TimeSpan from seconds.
  • TimeSpan.fromMinutes(minutes: number): TimeSpan — Creates a TimeSpan from minutes.
  • TimeSpan.fromHours(hours: number): TimeSpan — Creates a TimeSpan from hours.
  • TimeSpan.fromDays(days: number): TimeSpan — Creates a TimeSpan from days.

Instance Methods

  • milliseconds(): number — Returns the total number of milliseconds.
  • seconds(round = true): number — Returns the total number of seconds, optionally rounded.
  • minutes(round = true): number — Returns the total number of minutes, optionally rounded.
  • hours(round = true): number — Returns the total number of hours, optionally rounded.
  • days(round = true): number — Returns the total number of days, optionally rounded.
  • add(other: TimeSpan): TimeSpan — Adds another TimeSpan to this one.
  • subtract(other: TimeSpan): TimeSpan — Subtracts another TimeSpan from this one.
  • multiply(factor: number): TimeSpan — Multiplies the TimeSpan by a factor.
  • divide(divisor: number): TimeSpan — Divides the TimeSpan by a divisor.
  • equals(other: TimeSpan): boolean — Checks if the TimeSpan is equal to another.
  • lessThan(other: TimeSpan): boolean — Checks if the TimeSpan is less than another.
  • lessThanOrEqual(other: TimeSpan): boolean — Checks if the TimeSpan is less than or equal to another.
  • greaterThan(other: TimeSpan): boolean — Checks if the TimeSpan is greater than another.
  • greaterThanOrEqual(other: TimeSpan): boolean — Checks if the TimeSpan is greater than or equal to another.
  • isPast(): boolean — Checks if the TimeSpan represents a time in the past.
  • isFuture(): boolean — Checks if the TimeSpan represents a time in the future.
  • toString(): string — Converts the TimeSpan to a string of milliseconds.

Constants

The TIMES_IN_MILLISECONDS constant is used to define time unit conversions.

export const TIMES_IN_MILLISECONDS = {
	SECOND: 1_000,
	MINUTE: 1_000 * 60,
	HOUR: 1_000 * 60 * 60,
	DAY: 1_000 * 60 * 60 * 24,
	WEEK: 1_000 * 60 * 60 * 24 * 7,
	MONTH: 1_000 * 60 * 60 * 24 * 30,
	YEAR: 1_000 * 60 * 60 * 24 * 365,
} as const;
export const TIMES_IN_MILLISECONDS = {
SECOND: 1_000,
MINUTE: 1_000 * 60,
HOUR: 1_000 * 60 * 60,
DAY: 1_000 * 60 * 60 * 24,
WEEK: 1_000 * 60 * 60 * 24 * 7,
MONTH: 1_000 * 60 * 60 * 24 * 30,
YEAR: 1_000 * 60 * 60 * 24 * 365,
} as const;
import { TIMES_IN_MILLISECONDS } from './TimeSpan.constants.js';
/**
* Represents a time span.
*/
export class TimeSpan {
private readonly _milliseconds: number;
private constructor(milliseconds: number) {
this._milliseconds = milliseconds;
}
/**
* Creates a TimeSpan from the current time.
*
* @returns A TimeSpan instance representing the current time.
*/
public static fromNow(): TimeSpan {
return new TimeSpan(Date.now());
}
/**
* Creates a TimeSpan from a Date object.
*
* @param date - The Date object.
* @returns A TimeSpan instance representing the Date.
*/
public static fromDate(date: Date): TimeSpan {
return new TimeSpan(date.getTime());
}
/**
* Creates a TimeSpan from milliseconds.
*
* @param milliseconds - The number of milliseconds.
* @returns A TimeSpan instance.
*/
public static fromMilliseconds(milliseconds: number): TimeSpan {
return new TimeSpan(milliseconds);
}
/**
* Creates a TimeSpan from seconds.
*
* @param seconds - The number of seconds.
* @returns A TimeSpan instance.
*/
public static fromSeconds(seconds: number): TimeSpan {
return new TimeSpan(seconds * TIMES_IN_MILLISECONDS.SECOND);
}
/**
* Creates a TimeSpan from minutes.
*
* @param minutes - The number of minutes.
* @returns A TimeSpan instance.
*/
public static fromMinutes(minutes: number): TimeSpan {
return new TimeSpan(minutes * TIMES_IN_MILLISECONDS.MINUTE);
}
/**
* Creates a TimeSpan from hours.
*
* @param hours - The number of hours.
* @returns A TimeSpan instance.
*/
public static fromHours(hours: number): TimeSpan {
return new TimeSpan(hours * TIMES_IN_MILLISECONDS.HOUR);
}
/**
* Creates a TimeSpan from days.
*
* @param days - The number of days.
* @returns A TimeSpan instance.
*/
public static fromDays(days: number): TimeSpan {
return new TimeSpan(days * TIMES_IN_MILLISECONDS.DAY);
}
/**
* Gets the total milliseconds in the TimeSpan.
*
* @returns The total milliseconds.
*/
public milliseconds(): number {
return this._milliseconds;
}
/**
* Gets the total seconds in the TimeSpan.
*
* @returns The total seconds.
*/
public seconds(round = true): number {
return this.divideWithConditionalRound(TIMES_IN_MILLISECONDS.SECOND, round);
}
/**
* Gets the total minutes in the TimeSpan.
*
* @returns The total minutes.
*/
public minutes(round = true): number {
return this.divideWithConditionalRound(TIMES_IN_MILLISECONDS.MINUTE, round);
}
/**
* Gets the total hours in the TimeSpan.
*
* @returns The total hours.
*/
public hours(round = true): number {
return this.divideWithConditionalRound(TIMES_IN_MILLISECONDS.HOUR, round);
}
/**
* Gets the total days in the TimeSpan.
*
* @returns The total days.
*/
public days(round = true): number {
return this.divideWithConditionalRound(TIMES_IN_MILLISECONDS.DAY, round);
}
/**
* Adds another TimeSpan to this TimeSpan.
*
* @param other - The other TimeSpan.
* @returns A new TimeSpan representing the sum.
*/
public add(other: TimeSpan): TimeSpan {
return TimeSpan.fromMilliseconds(this._milliseconds + other._milliseconds);
}
/**
* Subtracts another TimeSpan from this TimeSpan.
*
* @param other - The other TimeSpan.
* @returns A new TimeSpan representing the difference.
*/
public subtract(other: TimeSpan): TimeSpan {
return TimeSpan.fromMilliseconds(this._milliseconds - other._milliseconds);
}
/**
* Multiplies this TimeSpan by a factor.
*
* @param factor - The factor to multiply by.
* @returns A new TimeSpan representing the product.
*/
public multiply(factor: number): TimeSpan {
return TimeSpan.fromMilliseconds(this._milliseconds * factor);
}
/**
* Divides this TimeSpan by a divisor.
*
* @param divisor - The divisor to divide by.
* @returns A new TimeSpan representing the quotient.
*/
public divide(divisor: number): TimeSpan {
return TimeSpan.fromMilliseconds(this._milliseconds / divisor);
}
/**
* Checks if this TimeSpan is equal to another TimeSpan.
*
* @param other - The other TimeSpan.
* @returns True if the TimeSpans are equal, otherwise false.
*/
public equals(other: TimeSpan): boolean {
return this._milliseconds === other._milliseconds;
}
/**
* Checks if this TimeSpan is less than another TimeSpan.
*
* @param other - The other TimeSpan.
* @returns True if this TimeSpan is less, otherwise false.
*/
public lessThan(other: TimeSpan): boolean {
return this._milliseconds < other._milliseconds;
}
/**
* Checks if this TimeSpan is less than or equal to another TimeSpan.
*
* @param other - The other TimeSpan.
* @returns True if this TimeSpan is less than or equal, otherwise false.
*/
public lessThanOrEqual(other: TimeSpan): boolean {
return this._milliseconds <= other._milliseconds;
}
/**
* Checks if this TimeSpan is greater than another TimeSpan.
*
* @param other - The other TimeSpan.
* @returns True if this TimeSpan is greater, otherwise false.
*/
public greaterThan(other: TimeSpan): boolean {
return this._milliseconds > other._milliseconds;
}
/**
* Checks if this TimeSpan is greater than or equal to another TimeSpan.
*
* @param other - The other TimeSpan.
* @returns True if this TimeSpan is greater than or equal, otherwise false.
*/
public greaterThanOrEqual(other: TimeSpan): boolean {
return this._milliseconds >= other._milliseconds;
}
/**
* Checks if this TimeSpan is in the past.
*/
public isPast(): boolean {
return this.lessThan(TimeSpan.fromNow());
}
/**
* Checks if this TimeSpan is in the future.
*/
public isFuture(): boolean {
return this.greaterThan(TimeSpan.fromNow());
}
public toString(): string {
return this._milliseconds.toString();
}
private divideWithConditionalRound(divisor: number, round: boolean): number {
return round ? Math.round(this._milliseconds / divisor) : this._milliseconds / divisor;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment