CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/npm-moment-duration-format

A moment.js plugin for formatting durations with comprehensive template-based formatting and localization support.

Pending
Quality

Pending

Does it follow best practices?

Impact

Pending

No eval scenarios have been run

SecuritybySnyk

Pending

The risk profile of this skill

Overview
Eval results
Files

template-system.mddocs/

Template System

The template system provides flexible formatting control through moment tokens, escape sequences, auto-localization markers, and dynamic template functions.

Capabilities

Moment Tokens

Duration values are represented using moment token characters that correspond to time units.

// Duration tokens (case-insensitive alternatives where noted):
// Y or y: years
// M: months (no alternative - lowercase 'm' is minutes)
// W or w: weeks  
// D or d: days
// H or h: hours
// m: minutes (lowercase only)
// s: seconds (lowercase only)
// S: milliseconds (uppercase only)

Usage Examples:

var duration = moment.duration({
    years: 1,
    months: 2, 
    days: 3,
    hours: 4,
    minutes: 5,
    seconds: 6,
    milliseconds: 789
});

// Basic token usage
duration.format("y M d h m s S");
// "1 2 3 4 5 6 789"

// Case variations where available
duration.format("Y y W w D d H h");
// "1 1 0 0 3 3 4 4"

Token Length and Padding

Token length controls zero-padding for consistent output formatting.

// Single token: no padding
// Multiple tokens: zero-padded to token length
// Examples: h vs hh vs hhh

Usage Examples:

var duration = moment.duration(5, "minutes");

// Different padding levels
duration.format("m");      // "5"
duration.format("mm");     // "05" 
duration.format("mmm");    // "005"
duration.format("mmmm");   // "0005"

// Common time format patterns
moment.duration(3661, "seconds").format("h:mm:ss");    // "1:01:01"
moment.duration(3661, "seconds").format("hh:mm:ss");   // "01:01:01"

// Large value padding
moment.duration(1234, "minutes").format("hh:mm");      // "20:34"
moment.duration(1234, "minutes").format("hhh:mm");     // "020:34"

Multiple Token Instances

Tokens can appear multiple times in a template, but all instances must share the same length.

var duration = moment.duration(15, "seconds");

// All instances use the length of the first occurrence
duration.format("ssss sss ss s");        // "0015 0015 0015 0015"
duration.format("s ss sss ssss");        // "15 15 15 15"

// Mixed lengths in time formats
duration.format("h:mm h:m");             // "0:00 0:0" (mm forces 2-digit, m stays 1-digit)

Milliseconds Special Case

Token length of 2 for milliseconds creates a special truncated output for timer displays.

// SS token: pad to 3 digits, then truncate from left to show 2 digits
moment.duration(9, "milliseconds").format("mm:ss:SS");     // "00:00:00"
moment.duration(10, "milliseconds").format("mm:ss:SS");    // "00:00:01"
moment.duration(999, "milliseconds").format("mm:ss:SS");   // "00:00:99"
moment.duration(1011, "milliseconds").format("mm:ss:SS");  // "00:01:01"

// Compare with normal S and SSS tokens
moment.duration(1011, "milliseconds").format("S");         // "11"
moment.duration(1011, "milliseconds").format("SSS");       // "011"

Escape Sequences

Square brackets escape literal text in templates, preventing token interpretation.

// [text] - Escapes text, preventing moment token interpretation
// Escaped text appears literally in output

Usage Examples:

var duration = moment.duration(123, "minutes");

// Basic escaping
duration.format("h [hours] m [minutes]");
// "2 hours 3 minutes"

// Escaping prevents token interpretation
duration.format("h [h] m [m]");  
// "2 h 3 m" (not "2 2 3 3")

// Complex text escaping
duration.format("h [hrs,] m [mins]");
// "2 hrs, 3 mins"

// Escaping special characters
duration.format("h[:]mm");
// "2:03"

Auto-Localization Markers

Special markers that are replaced with localized content based on moment locale settings.

// _ (single underscore): replaced with short duration labels
// __ (double underscore): replaced with standard duration labels
// _HMS_: replaced with localized hour:minute:second template
// _HM_: replaced with localized hour:minute template  
// _MS_: replaced with localized minute:second template

Usage Examples:

// Unit label auto-localization
moment.duration(2, "minutes").format("m _");      // "2 mins"
moment.duration(2, "minutes").format("m __");     // "2 minutes"
moment.duration(1, "minute").format("m __");      // "1 minute" (auto-pluralized)

// Time notation templates
moment.duration(3661, "seconds").format("_HMS_"); // "1:01:01"
moment.duration(3661, "seconds").format("_HM_");  // "1:01"
moment.duration(61, "seconds").format("_MS_");    // "1:01"

// Combined usage
moment.duration(7322, "seconds").format("_HMS_ [total]");
// "2:02:02 total"

Stop Trim Markers

The asterisk (*) prefix marks tokens where trimming should stop.

// *token - Marks token as stopTrim, preventing further trimming
// Equivalent to adding token to stopTrim setting array

Usage Examples:

var duration = moment.duration(23, "minutes");

// Without stop trim marker
duration.format("d[d] h:mm:ss");
// "23:00"

// With stop trim marker on hours
duration.format("d[d] *h:mm:ss"); 
// "0:23:00"

// Multiple stop trim markers
moment.duration(2, "hours").format("y [years], *d [days], h [hours], *m [minutes], s [seconds]", {
    trim: "both"
});
// "0 days, 2 hours, 0 minutes"

Template Functions

Dynamic Template Generation

Template functions enable runtime template selection based on duration values or other conditions.

/**
 * Template function executed with 'this' bound to settings object
 * @returns Template string to use for formatting
 */
function templateFunction(): string;

// Available context:
// this.duration - The duration being formatted
// this.types - Array of token types
// All other settings properties available via 'this'

Usage Examples:

function adaptiveTemplate() {
    var duration = this.duration;
    var totalSeconds = duration.asSeconds();
    
    if (totalSeconds < 60) {
        return "s [seconds]";
    } else if (totalSeconds < 3600) {
        return "m:ss";
    } else if (totalSeconds < 86400) {
        return "h:mm:ss";
    } else {
        return "d [days], h:mm:ss";
    }
}

// Usage with different duration magnitudes
moment.duration(30, "seconds").format(adaptiveTemplate);
// "30 seconds"

moment.duration(90, "seconds").format(adaptiveTemplate);  
// "1:30"

moment.duration(3661, "seconds").format(adaptiveTemplate);
// "1:01:01"

moment.duration(90061, "seconds").format(adaptiveTemplate);
// "1 days, 1:01:01"

Settings-Based Templates

Template functions can access and modify settings dynamically:

function conditionalTemplate() {
    var duration = this.duration;
    
    // Modify settings based on duration
    if (duration.asHours() >= 24) {
        this.trim = "both";
        return "w [weeks], d [days], h [hours]";
    } else {
        this.trim = "large";
        return "h:mm:ss";
    }
}

moment.duration(25, "hours").format(conditionalTemplate);
// "1 day, 1 hour" (with trim: "both")

moment.duration(2, "hours").format(conditionalTemplate);
// "2:00:00" (with trim: "large")

Access to Token Types

Template functions can inspect available token types for decision making:

function intelligentTemplate() {
    var types = this.types; // Available: ["escape", "years", "months", ...]
    var duration = this.duration;
    
    // Check what units the duration actually has
    var hasYears = duration.years() > 0;
    var hasMonths = duration.months() > 0;
    var hasDays = duration.days() > 0;
    
    if (hasYears || hasMonths) {
        return "y [years], M [months], d [days]";
    } else if (hasDays) {
        return "d [days], h:mm:ss";
    } else {
        return "h:mm:ss";
    }
}

Template Processing Order

Templates are processed in the following sequence:

  1. Template Function Execution: If template is a function, execute with settings context
  2. Time Template Replacement: Replace _HMS_, _HM_, _MS_ with locale templates
  3. Token Parsing: Parse template for moment tokens and escape sequences
  4. Token Association: Associate text tokens with moment tokens
  5. Value Calculation: Calculate values for each token type
  6. Formatting: Apply number formatting and localization
  7. Trimming: Apply trimming rules to remove zero-value tokens
  8. Label Processing: Apply auto-localization and pluralization
  9. Output Assembly: Combine tokens with their text to create final output

docs

configuration-settings.md

duration-formatting.md

index.md

localization.md

multiple-duration-formatting.md

template-system.md

tile.json