Tempo Date and Time Library

website·Indexed 35 days ago

https://tempo.formkit.com

A tiny, tree-shakable JavaScript library for date and time manipulation and timezone management, featuring formatting capabilities, timezone settings, and utility functions like monthStart and removeOffset.

Tokens
2.7K
Snippets
21
Records
22
Agent score
17%

What's inside Tempo

  1. Convert dates to a specific timezone during formatting

    Use the tz option within the format() function to display a date from the perspective of a specific timezone. For example, a UTC date can be converted to 'America/New_York' time during the formatting process.
    import { format } from '@formkit/tempo'
    
    format({
      date: new Date('2021-01-01T00:00:00Z'),
      tz: 'America/New_York',
      format: 'YYYY-MM-DD HH:mm:ss'
    })
    // Output: 2020-12-31 19:00:00
  2. Install Tempo

    Tempo is a tiny, tree-shakable library for date and time manipulation. It is available as the @formkit/tempo package.
    # npm
    npm install @formkit/tempo
    
    # pnpm
    pnpm add @formkit/tempo
    
    # yarn
    yarn add @formkit/tempo
    
    # bun
    bun install @formkit/tempo
  3. Set specific date and time components

    Tempo provides a set of functions to modify specific components of a Date object. Most of these functions accept either a Date object or an ISO 8601 string. For functions that modify the day, month, or year, the dateOverflow parameter (default false) determines if values beyond the valid range should clamp to the last day of the month or overflow into the next period.
    import { 
      setDayOfMonth, 
      setMonth, 
      setYear, 
      setHour, 
      setMinutes, 
      setSeconds, 
      setMilliseconds 
    } from 'tempo'
    
    // Set day to 15th, clamp if it exceeds month length
    setDayOfMonth(new Date(), 15, false);
    
    // Set month to February (0-indexed, 0=Jan), allow overflow
    setMonth(new Date(), 1, true);
    
    // Set year
    setYear(new Date(), 2024, false);
    
    // Set time components
    setHour(new Date(), 13);
    setMinutes(new Date(), 30);
    setSeconds(new Date(), 45);
    setMilliseconds(new Date(), 500);
  4. Calculate time difference in specific units with rounding

    Tempo provides a set of diff functions to calculate the difference between two dates in specific units. These functions accept an optional roundingMethod parameter to handle partial units. Supported rounding methods are: trunc, round, floor, and ceil.
    // Available functions:
    function diffSeconds(dateA: string | Date, dateB: string | Date, roundingMethod: "trunc" | "round" | "floor" | "ceil"): number
    function diffMinutes(dateA: string | Date, dateB: string | Date, roundingMethod: "trunc" | "round" | "floor" | "ceil"): number
    function diffHours(dateA: string | Date, dateB: string | Date, roundingMethod: "trunc" | "round" | "floor" | "ceil"): number
    function diffDays(dateA: string | Date, dateB: string | Date, roundingMethod: "trunc" | "round" | "floor" | "ceil"): number
    function diffWeeks(dateA: string | Date, dateB: string | Date, roundingMethod: "trunc" | "round" | "floor" | "ceil"): number
    function diffMonths(dateA: string | Date, dateB: string | Date, roundingMethod: "trunc" | "round" | "floor" | "ceil"): number
  5. Apply timezone offsets and ISO conversion

    Tempo provides utilities for handling timezone offsets and basic ISO string conversion.
    // Apply a timezone offset (e.g., -0800)
    const offsetDate = applyOffset(new Date(), '-0800');
    
    // Convert ISO 8601-like string to Date (requires at least year and month)
    const dateObj = date('2023-01');
  6. Add duration to a date

    The add function returns a new Date object with a specified duration applied. To subtract time, use negative numbers in the duration object. Month and year overflow behavior is controlled by the dateOverflow boolean (defaults to false).
    interface Duration {
      years?: number;
      months?: number;
      weeks?: number;
      days?: number;
      hours?: number;
      minutes?: number;
      seconds?: number;
      milliseconds?: number;
    }
    
    const newDate = add(new Date(), { months: 1, days: 5 });
  7. Calculate the difference between two dates as a duration

    Use the diff function to calculate the difference between two dates. It returns a duration object containing years, months, weeks, days, hours, minutes, seconds, and milliseconds. The result can be passed to the add function or formatted using Intl.DurationFormat.
    interface Duration {
      years?: number;
      months?: number;
      weeks?: number;
      days?: number;
      hours?: number;
      minutes?: number;
      seconds?: number;
      milliseconds?: number;
    }
    
    interface DiffOptions {
      abs?: boolean; // Return absolute values instead of signed values
      skip?: Array<keyof Duration> | Set<keyof Duration>; // Units to omit while calculating the duration
    }
  8. Calculate millisecond difference between two dates

    The diffMilliseconds function returns the total number of milliseconds difference between two date objects (provided as strings or Date objects).
    function diffMilliseconds(
      dateA: string | Date,
      dateB: string | Date
    ): number
  9. Format dates and times using the format() function

    The format() function allows you to output dates using either predefined international styles (via Intl.DateTimeFormat) or custom format tokens. It accepts a Date object or an ISO 8601 string.
    import { format } from '@formkit/tempo'
    
    // Using a format token
    format(new Date(), 'YYYY-MM-DD')
    
    // Using a date style
    format(new Date(), { date: 'long' })
    
    // Using a time style
    format(new Date(), { time: 'medium' })
    
    // Using both date and time styles
    format(new Date(), { date: 'short', time: 'short' })
  10. Set date and time boundaries

    Use these utility functions to snap a date to the start or end of a specific time unit (local time).
    dayStart(date);   // 00:00:00.000
    dayEnd(date);     // 23:59:59.999
    hourStart(date);  // Minutes set to 00:00.000
    hourEnd(date);    // Minutes set to 59:59.999
    minuteStart(date); // Seconds set to 00.000
    minuteEnd(date);    // Seconds set to 59.999
    monthStart(date);  // First day of current month
    monthEnd(date);    // Last day of current month
  11. Parse a date string into a Date object

    The parse function converts a date string into a JavaScript Date object. It can parse any output generated by the format function, including style formats. Since JavaScript Date objects always include both date and time, any undefined portions of the parsed date will default to the current date at midnight local time.
    // Basic usage
    const date = parse('2023-01-01', 'YYYY-MM-DD');
    
    // Using options object
    const dateWithOpts = parse({
      date: 'February 29, 2023',
      format: 'MMMM D, YYYY',
      locale: 'en-US',
      dateOverflow: 'backward' // Result: February 28, 2023
    });
  12. Extract date and timezone data

    Tempo provides utility functions to extract metadata from dates without mutating the original object.
    import { dayOfYear, monthDays, yearDays, iso8601 } from 'tempo'
    
    const date = new Date();
    
    const dayNum = dayOfYear(date); // e.g., 213
    const daysInMonth = monthDays(date);
    const daysInYear = yearDays(date);
    const isValidIso = iso8601(date); // Validates if date is acceptable ISO 8601