TypeScript Function to Convert Date Time to Time Ago (2 examples)

Updated: February 23, 2024 By: Guest Contributor Post a comment

Overview

Handling dates and times effectively is a common challenge in web development, often involving displaying timestamps in a more human-readable form such as ‘2 hours ago’ or ‘yesterday.’ TypeScript, an enhanced version of JavaScript, provides powerful typing and object-oriented features that can make this task more manageable and less error-prone. This tutorial will guide you through the process of creating functions in TypeScript to convert Date objects into a friendly ‘time ago’ format. We’ll provide two examples: a basic implementation and a more advanced version with localization support.

Prerequisites

Before getting started, make sure you have the following:

  • Basic understanding of TypeScript/JavaScript
  • Node.js installed on your machine (for running TypeScript code)
  • Text editor, such as Visual Studio Code

Example 1: Basic ‘Time Ago’ Function

Let’s start with a simple TypeScript function that converts a Date object into a ‘time ago’ string. This function will cover minutes, hours, days, months, and years.

function timeAgo(datePast: Date): string {
  const seconds = Math.floor((new Date().getTime() - datePast.getTime()) / 1000);
  const minutes = Math.floor(seconds / 60);
  const hours = Math.floor(minutes / 60);
  const days = Math.floor(hours / 24);
  const months = Math.floor(days / 30);
  const years = Math.floor(days / 365);

  if (seconds < 60) {
    return 'just now';
  } else if (minutes < 60) {
    return minutes + ' minutes ago';
  } else if (hours < 24) {
    return hours + ' hours ago';
  } else if (days < 30) {
    return days + ' days ago';
  } else if (months < 12) {
    return months + ' months ago';
  } else {
    return years + ' years ago';
  }
}

This example function takes a Date object as its argument and compares it with the current date and time to calculate the difference in various time units.

Example 2: Advanced ‘Time Ago’ Function with Localization

Now, let’s enhance our ‘time ago’ function by adding support for localization, allowing it to display time-related terms (such as ‘days’, ‘hours’, etc.) in different languages. This function will have an added parameter for the language code (e.g., ‘en’ for English, ‘es’ for Spanish).

interface TimeAgoOptions {
  locale?: string;
}

function timeAgoLocale(datePast: Date, options: TimeAgoOptions = {}): string {
  const { locale = 'en' } = options;
  const seconds = Math.floor((new Date().getTime() - datePast.getTime()) / 1000);
  // Localization logic (would usually fetch or calculate based on locale)
  const terms = {
    en: {
      justNow: 'just now',
      minutes: 'minutes ago',
      hours: 'hours ago',
      days: 'days ago',
      months: 'months ago',
      years: 'years ago'
    },
    es: {
      justNow: 'justo ahora',
      minutes: 'minutos antes',
      hours: 'horas antes',
      days: 'días antes',
      months: 'meses antes',
      years: 'años antes'
    }
    // Add more languages as needed
  };

  if (seconds < 60) {
    return terms[locale].justNow;
  } else if (minutes < 60) {
    return minutes + ' ' + terms[locale].minutes;
  } else if (hours < 24) {
    return hours + ' ' + terms[locale].hours;
  } else if (days < 30) {
    return days + ' ' + terms[locale].days;
  } else if (months < 12) {
    return months + ' ' + terms[locale].months;
  } else {
    return years + ' ' + terms[locale].years;
  }
}

This function improves upon the first example by incorporating an interface for option parameters, with locale being optional. It demonstrates how you might structure your function to support multiple languages, basing the output on the chosen locale.

Conclusion

These examples illustrate how TypeScript’s type system and JavaScript’s Date API can work together to create practical utilities for web applications. The first example provided a foundational approach to calculating ‘time ago’ strings, while the second example introduced localization, making your application more accessible to a global audience. Whether you’re working on social media posts, comment sections, or any feature that benefits from displaying timestamps in a friendly manner, these functions offer a solid starting point for further customization and improvement.

Remember, handling dates and times correctly is crucial for many applications, and paying attention to details like localization can significantly enhance user experience. By leveraging TypeScript’s features, you can build reliable and user-friendly date and time utilities.