Jiffy

repository·master·Indexed 20 days ago

https://github.com/jama5262/jiffy

A Flutter and Dart package for parsing, manipulating, querying, and formatting dates and times across Android, iOS, and Web platforms. It provides tools for ISO 8601 and custom pattern parsing, relative time calculations (e.g., fromNow, toNow), date manipulation via add/subtract and startOf/endOf, and comprehensive locale support including custom ordinal suffixes and relative date-time formatting.

Tokens
9.5K
Snippets
32
Records
46
Agent score
70%

What's inside Jiffy

  1. Customize the start of the week

    master

    By default, locales have a defined start of the week (e.g., en_US uses StartOfWeek.sunday). You can override this globally using Jiffy.setLocale with the startOfWeek parameter, which accepts values from the StartOFWeek enum (e.g., StartOFWeek.monday, StartOFWeek.saturday).

    await Jiffy.setLocale(
        locale: 'en_US',
        startOfWeek: StartOFWeek.saturday,
    );
  2. Manipulate dates with add, subtract, and boundaries

    master

    You can modify Jiffy instances using .add() and .subtract() with various time units (days, hours, minutes, months, etc.). You can also snap a date to the start or end of a specific time unit using .startOf(Unit) and .endOf(Unit) most common units are Unit.yearandUnit.month`.

    // Adding and subtracting
    var jiffy = Jiffy.now().add(days: 1);
    var complex = Jiffy.now()
      .add(hours: 3, days: 1)
      .subtract(minutes: 30, months: 1);
    
    // Setting boundaries
    Jiffy.parse('1997/09/23').startOf(Unit.year);
    Jiffy.parse('1997/09/23').endOf(Unit.month);
  3. Calculate relative time

    master

    Jiffy allows you to express the difference between two dates in human-readable relative terms (e.g., "5 years ago" or "in 5 years").

    • Use .from(otherJiffy) or .fromNow() to calculate time elapsed from a point in the past.
    • Use .to(otherJiffy) or .toNow() to calculate time remaining until a point in the future.
    // From a specific date
    Jiffy.parse('1997/09/23').from(Jiffy.parse('2002/10/26')); // 5 years ago
    
    // From now
    Jiffy.parse('1997/09/23').fromNow(); // 25 years ago
    
    // To a specific date
    Jiffy.parse('1997/09/23').to(Jiffy.parse('2002/10/26')); // in 5 years
    
    // To now
    Jiffy.parse('1997/09/23').toNow(); // in 25 years
  4. Set and configure locales in Jiffy

    master

    Jiffy supports all locales provided by the intl package. Note: Jiffy.setLocale always returns a Future and must be awaited.

    Basic Locale Setting

    To change the global locale for Jiffy:

    await Jiffy.setLocale('fr');

    Advanced Locale Configuration

    You can provide a custom configuration object to override default behaviors for a locale, such as the start of the week, ordinal suffixes, and relative date-time formatting.

    await Jiffy.setLocale(
      locale: 'en_US',
      startOfWeek: StartOFWeek.monday,
      ordinals: Ordinals(first: "st", second: "nd", third: "rd", nth: "th"),
      relativeDateTime: EnRelativeDateTime()
    );
  5. Query date relationships

    master

    Use comparison methods to check the relationship between two Jiffy instances:

    • .isBefore(other): Returns true if the instance is before the provided date.
    • .isAfter(other): Returns true if the instance is after the provided date.
    • .isSame(other): Returns true if the instances represent the same time.
    • .isBetween(start, end): Returns true if the instance falls within the range of the two provided dates.
    Jiffy.parse('1997/9/23').isBefore(Jiffy.parse('1997/9/24')); // true
    Jiffy.parse('1997/9/23').isAfter(Jiffy.parse('1997/9/20')); // true
    Jiffy.parse('1997/9/23').isSame(Jiffy.parse('1997/9/23')); // true
    Jiffy.parse('1997/9/23').isBetween(Jiffy.parse('1997/9/20'), Jiffy.parse('1997/9/24')); // true
  6. Format dates with Jiffy

    master

    Jiffy provides multiple ways to format dates into human-readable strings. You can use the .format() method with a custom pattern or use convenient pre-set getter properties (like .yMMMMd) for common formats.

    Parsing can be done from strings, lists, or maps. When parsing a string with a non-standard format, provide the pattern to the parse method.

    // Custom patterns
    Jiffy.parse('2021/01/19').format(pattern: 'MMMM do yyyy, h:mm:ss a'); 
    Jiffy.now().format(pattern: 'EEEE'); 
    
    // Pre-set formats (getters)
    Jiffy.parseFromList([2020, 10, 19]).yMMMMd; 
    
    // Parsing from a Map using Unit enum
    Jiffy.parseFromMap({
      Unit.year: 2020,
      Unit.month: 10,
      Unit.day: 19,
      Unit.hour: 19
    }).dMMMMEEEEyjm;
    
    // Parsing with a specific pattern
    Jiffy.parse('19, Jan 2021', pattern: 'dd, MMM yyyy').yMMMMd;
  7. Customize ordinal suffixes

    master

    Ordinals are suffixes like 'st', 'nd', 'rd', and 'th' used in date formatting (e.g., '1st'). If a locale's default ordinals are not suitable or supported, you can provide a custom Ordinals object when calling Jiffy.setLocale.

    await Jiffy.setLocale(
        locale: 'en_US',
        ordinals: Ordinals(first: "st", second: "nd", third: "rd", nth: "th"),
    );
  8. Configure locale support in Jiffy

    master

    Jiffy supports localization for date formatting. You can check the current locale using .localeCode and change the global locale for all subsequent Jiffy operations using the asynchronous await Jiffy.setLocale(localeCode) method. Supported locale codes include en_US, fr_ca, ja, and zh_cn.

    // Get current locale
    String code = Jiffy.now().localeCode; 
    
    // Set a new locale
    await Jiffy.setLocale('fr_ca');
    Jiffy.now().yMMMMEEEEdjm; // dimanche 26 février 2023 12 h 03
    
    await Jiffy.setLocale('ja');
    Jiffy.now().yMMMMEEEEdjm; // 2023年2月26日日曜日 12:02
  9. Implement custom Relative Date Time formatting

    master

    Relative date-time expresses time differences in human-readable formats (e.g., '14 years ago'). To customize this behavior, you can create a class that extends the RelativeDateTime abstract class or extends an existing implementation like EnRelativeDateTime.

    Extending RelativeDateTime (Full Customization)

    Implement all required methods like prefixAgo, suffixAgo, minutes, hours, etc.

    Extending EnRelativeDateTime (Partial Customization)

    Override only the specific methods you wish to change.

    class CustomRelativeDateTime extends EnRelativeDateTime {
      @override
      String suffixAgo() => 'ago, i think';
      @override
      String aDay(int hours) => 'like a day';
    }
    
    await Jiffy.setLocale(
        locale: 'en_US',
        relativeDateTime: CustomRelativeDateTime(),
    );
  10. Understand the RelativeDateTime abstraction

    master

    The RelativeDateTime class is an abstract interface used by Jiffy to provide localized strings for relative time expressions (e.g., "ago", "in", "minutes", "hours").

    When Jiffy performs relative time formatting, it uses an implementation of this class corresponding to the active locale. This allows the library to handle complex linguistic rules, such as different word orders (prefixes vs. suffixes), pluralization rules, and locale-specific numbering systems (e.g., Arabic or Persian numerals).

    Key methods provided by the interface include:

    • prefixAgo() / suffixAgo(): Strings to wrap a duration for past events.
    • prefixFromNow() / suffixFromNow(): Strings to wrap a duration for future events.
    • lessThanOneMinute(int seconds): A localized string for very short durations.
    • aboutAMinute(int minutes), aboutAnHour(int minutes), aboutAMonth(int days), aboutAYear(int year): Strings for approximate durations.
    • minutes(int minutes), hours(int hours), days(int days), months(int months), years(int years): Pluralized duration strings.
    • wordSeparator(): The character used to separate words in the relative string.
  11. Understand the Locale configuration structure

    master

    In Jiffy, a Locale object encapsulates all internationalization rules for a specific language and region. When implementing or extending locale support, a Locale must define four key components:

    1. code: A unique string identifier (e.g., "en_US", "fr_CA").
    2. startOfWeek: A StartOfWeek enum value indicating which day the week begins for that locale.
    3. ordinals: An Ordinals object containing the suffixes used for ordinal numbers (e.g., "st", "nd", "rd", "th").
    4. relativeDateTime: A RelativeDateTime instance that defines the rules for formatting relative time strings (e.g., "3 hours ago" or "in 2 days").
  12. Configure the Jiffy locale

    master

    Use Jiffy.setLocale to set the global locale for Jiffy instances. This affects date formatting, relative time strings, and the start of the week. You can also customize startOfWeek, ordinals, and relativeDateTime settings during setup.

    Supported locales can be retrieved using Jiffy.getSupportedLocales().

    await Jiffy.setLocale('en_US');
    await Jiffy.setLocale('en_US', startOfWeek: StartOfWeek.monday);
    
    final supportLocales = Jiffy.getSupportedLocales();
    print(supportLocales); // ['en_us', 'en', 'fr', ...]