Huge News!Announcing our $40M Series B led by Abstract Ventures.Learn More
Socket
Sign inDemoInstall
Socket

date-fns-format

Package Overview
Dependencies
Maintainers
1
Versions
1
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

date-fns-format

Format options for date-fns

  • 0.0.1
  • latest
  • npm
  • Socket score

Version published
Weekly downloads
2
increased by100%
Maintainers
1
Weekly downloads
 
Created
Source

Date: 2024-04-29 Title: Date Format Utility with date-fns

Date Format Utility with date-fns

Introduction

This document describes the use of the DateFormat enum in conjunction with date-fns to standardize date formatting across a JavaScript/TypeScript project. By encapsulating commonly used date format strings into an enum, we enhance code readability, maintainability, and reduce the risk of typos and inconsistencies.

Overview

The DateFormat enum includes a comprehensive list of date format options that can be used with the date-fns library to format dates. This approach standardizes date formatting throughout the application and ensures consistency across different parts of the application.

Installation

First, ensure that you have date-fns installed in your project. If not, you can add it by running:

npm install date-fns

Usage

Here’s how to use the DateFormat enum in your project:

Basic Usage

Import the enum and the format function from date-fns wherever you need to format dates:

import { format } from 'date-fns';
import { DateFormat } from 'date-fns-format';

const today = new Date();
const formattedDate = format(today, DateFormat.YearFourDigits);
console.log('Formatted Year:', formattedDate);

Advanced Usage

You can use the enum in more complex scenarios such as components or services where multiple date formats are required:

import { format } from 'date-fns';
import { DateFormat } from './path/to/DateFormat';

const logFormattedDates = (date: Date) => {
    console.log('Full Date:', format(date, DateFormat.LongLocalizedDate));
    console.log('Month:', format(date, DateFormat.MonthFull));
    console.log('Weekday:', format(date, DateFormat.DayOfWeekFull));
}

Benefits

-Consistency*: Using the enum ensures that date formats are consistent throughout the application. -Maintenance*: Easy to update and maintain date formats in one location. -Readability*: More readable codebase with clear references to date formats instead of raw strings.

Conclusion

Using the DateFormat enum with date-fns enhances your project's date handling by providing a clear, maintainable method for dealing with date formats. This method reduces errors and improves the development experience.

Table Display

Accepted patterns:

UnitPatternResult examplesNotes
EraG..GGGAD, BC
GGGGAnno Domini, Before Christ2
GGGGGA, B
Calendar yeary44, 1, 1900, 20175
yo44th, 1st, 0th, 17th5,7
yy44, 01, 00, 175
yyy044, 001, 1900, 20175
yyyy0044, 0001, 1900, 20175
yyyyy...3,5
Local week-numbering yearY44, 1, 1900, 20175
Yo44th, 1st, 1900th, 2017th5,7
YY44, 01, 00, 175,8
YYY044, 001, 1900, 20175
YYYY0044, 0001, 1900, 20175,8
YYYYY...3,5
ISO week-numbering yearR-43, 0, 1, 1900, 20175,7
RR-43, 00, 01, 1900, 20175,7
RRR-043, 000, 001, 1900, 20175,7
RRRR-0043, 0000, 0001, 1900, 20175,7
RRRRR...3,5,7
Extended yearu-43, 0, 1, 1900, 20175
uu-43, 01, 1900, 20175
uuu-043, 001, 1900, 20175
uuuu-0043, 0001, 1900, 20175
uuuuu...3,5
Quarter (formatting)Q1, 2, 3, 4
Qo1st, 2nd, 3rd, 4th7
QQ01, 02, 03, 04
QQQQ1, Q2, Q3, Q4
QQQQ1st quarter, 2nd quarter, ...2
QQQQQ1, 2, 3, 44
Quarter (stand-alone)q1, 2, 3, 4
qo1st, 2nd, 3rd, 4th7
qq01, 02, 03, 04
qqqQ1, Q2, Q3, Q4
qqqq1st quarter, 2nd quarter, ...2
qqqqq1, 2, 3, 44
Month (formatting)M1, 2, ..., 12
Mo1st, 2nd, ..., 12th7
MM01, 02, ..., 12
MMMJan, Feb, ..., Dec
MMMMJanuary, February, ..., December2
MMMMMJ, F, ..., D
Month (stand-alone)L1, 2, ..., 12
Lo1st, 2nd, ..., 12th7
LL01, 02, ..., 12
LLLJan, Feb, ..., Dec
LLLLJanuary, February, ..., December2
LLLLLJ, F, ..., D
Local week of yearw1, 2, ..., 53
wo1st, 2nd, ..., 53th7
ww01, 02, ..., 53
ISO week of yearI1, 2, ..., 537
Io1st, 2nd, ..., 53th7
II01, 02, ..., 537
Day of monthd1, 2, ..., 31
do1st, 2nd, ..., 31st7
dd01, 02, ..., 31
Day of yearD1, 2, ..., 365, 3669
Do1st, 2nd, ..., 365th, 366th7
DD01, 02, ..., 365, 3669
DDD001, 002, ..., 365, 366
DDDD...3
Day of week (formatting)E..EEEMon, Tue, Wed, ..., Sun
EEEEMonday, Tuesday, ..., Sunday2
EEEEEM, T, W, T, F, S, S
EEEEEEMo, Tu, We, Th, Fr, Sa, Su
ISO day of week (formatting)i1, 2, 3, ..., 77
io1st, 2nd, ..., 7th7
ii01, 02, ..., 077
iiiMon, Tue, Wed, ..., Sun7
iiiiMonday, Tuesday, ..., Sunday2,7
iiiiiM, T, W, T, F, S, S7
iiiiiiMo, Tu, We, Th, Fr, Sa, Su7
Local day of week (formatting)e2, 3, 4, ..., 1
eo2nd, 3rd, ..., 1st7
ee02, 03, ..., 01
eeeMon, Tue, Wed, ..., Sun
eeeeMonday, Tuesday, ..., Sunday2
eeeeeM, T, W, T, F, S, S
eeeeeeMo, Tu, We, Th, Fr, Sa, Su
Local day of week (stand-alone)c2, 3, 4, ..., 1
co2nd, 3rd, ..., 1st7
cc02, 03, ..., 01
cccMon, Tue, Wed, ..., Sun
ccccMonday, Tuesday, ..., Sunday2
cccccM, T, W, T, F, S, S
ccccccMo, Tu, We, Th, Fr, Sa, Su
AM, PMa..aaAM, PM
aaaam, pm
aaaaa.m., p.m.2
aaaaaa, p
AM, PM, noon, midnightb..bbAM, PM, noon, midnight
bbbam, pm, noon, midnight
bbbba.m., p.m., noon, midnight2
bbbbba, p, n, mi
Flexible day periodB..BBBat night, in the morning, ...
BBBBat night, in the morning, ...2
BBBBBat night, in the morning, ...
Hour [1-12]h1, 2, ..., 11, 12
ho1st, 2nd, ..., 11th, 12th7
hh01, 02, ..., 11, 12
Hour [0-23]H0, 1, 2, ..., 23
Ho0th, 1st, 2nd, ..., 23rd7
HH00, 01, 02, ..., 23
Hour [0-11]K1, 2, ..., 11, 0
Ko1st, 2nd, ..., 11th, 0th7
KK01, 02, ..., 11, 00
Hour [1-24]k24, 1, 2, ..., 23
ko24th, 1st, 2nd, ..., 23rd7
kk24, 01, 02, ..., 23
Minutem0, 1, ..., 59
mo0th, 1st, ..., 59th7
mm00, 01, ..., 59
Seconds0, 1, ..., 59
so0th, 1st, ..., 59th7
ss00, 01, ..., 59
Fraction of secondS0, 1, ..., 9
SS00, 01, ..., 99
SSS000, 001, ..., 999
SSSS...3
Timezone (ISO-8601 w/ Z)X-08, +0530, Z
XX-0800, +0530, Z
XXX-08:00, +05:30, Z
XXXX-0800, +0530, Z, +1234562
XXXXX-08:00, +05:30, Z, +12:34:56
Timezone (ISO-8601 w/o Z)x-08, +0530, +00
xx-0800, +0530, +0000
xxx-08:00, +05:30, +00:002
xxxx-0800, +0530, +0000, +123456
xxxxx-08:00, +05:30, +00:00, +12:34:56
Timezone (GMT)O...OOOGMT-8, GMT+5:30, GMT+0
OOOOGMT-08:00, GMT+05:30, GMT+00:002
Timezone (specific non-locat.)z...zzzGMT-8, GMT+5:30, GMT+06
zzzzGMT-08:00, GMT+05:30, GMT+00:002,6
Seconds timestampt5129695207
tt...3,7
Milliseconds timestampT5129695209007
TT...3,7
Long localized dateP04/29/14537
PPApr 29, 14537
PPPApril 29th, 14537
PPPPFriday, April 29th, 14532,7
Long localized timep12:00 AM7
pp12:00:00 AM7
ppp12:00:00 AM GMT+27
pppp12:00:00 AM GMT+02:002,7
Combination of date and timePp04/29/1453, 12:00 AM7
PPppApr 29, 1453, 12:00:00 AM7
PPPpppApril 29th, 1453 at ...7
PPPPppppFriday, April 29th, 1453 at ...2,7

Notes:

  1. "Formatting" units (e.g. formatting quarter) in the default en-US locale are the same as "stand-alone" units, but are different in some languages. "Formatting" units are declined according to the rules of the language in the context of a date. "Stand-alone" units are always nominative singular:

    format(new Date(2017, 10, 6), 'do LLLL', {locale: cs}) //=> '6. listopad'

    format(new Date(2017, 10, 6), 'do MMMM', {locale: cs}) //=> '6. listopadu'

  2. Any sequence of the identical letters is a pattern, unless it is escaped by the single quote characters (see below). If the sequence is longer than listed in table (e.g. EEEEEEEEEEE) the output will be the same as default pattern for this unit, usually the longest one (in case of ISO weekdays, EEEE). Default patterns for units are marked with "2" in the last column of the table.

    format(new Date(2017, 10, 6), 'MMM') //=> 'Nov'

    format(new Date(2017, 10, 6), 'MMMM') //=> 'November'

    format(new Date(2017, 10, 6), 'MMMMM') //=> 'N'

    format(new Date(2017, 10, 6), 'MMMMMM') //=> 'November'

    format(new Date(2017, 10, 6), 'MMMMMMM') //=> 'November'

  3. Some patterns could be unlimited length (such as yyyyyyyy). The output will be padded with zeros to match the length of the pattern.

    format(new Date(2017, 10, 6), 'yyyyyyyy') //=> '00002017'

  4. QQQQQ and qqqqq could be not strictly numerical in some locales. These tokens represent the shortest form of the quarter.

  5. The main difference between y and u patterns are B.C. years:

    Yearyu
    AC 111
    BC 110
    BC 22-1

    Also yy always returns the last two digits of a year, while uu pads single digit years to 2 characters and returns other years unchanged:

    Yearyyuu
    10101
    141414
    37676376
    1453531453

    The same difference is true for local and ISO week-numbering years (Y and R), except local week-numbering years are dependent on options.weekStartsOn and options.firstWeekContainsDate (compare getISOWeekYear and getWeekYear).

  6. Specific non-location timezones are currently unavailable in date-fns, so right now these tokens fall back to GMT timezones.

  7. These patterns are not in the Unicode Technical Standard #35:

    • i: ISO day of week
    • I: ISO week of year
    • R: ISO week-numbering year
    • t: seconds timestamp
    • T: milliseconds timestamp
    • o: ordinal number modifier
    • P: long localized date
    • p: long localized time
  8. YY and YYYY tokens represent week-numbering years but they are often confused with years. You should enable options.useAdditionalWeekYearTokens to use them. See: unicodeTokens

  9. D and DD tokens represent days of the year but they are often confused with days of the month. You should enable options.useAdditionalDayOfYearTokens to use them. See: unicodeTokens

@typeParam DateType - The Date type, the function operates on. Gets inferred from passed arguments. Allows to use extensions like UTCDate.

@param date - The original date @param format - The string of tokens @param options - An object with options

@returns The formatted date string

@throws date must not be Invalid Date @throws options.locale must contain localize property @throws options.locale must contain formatLong property @throws use yyyy instead of YYYY for formatting years using [format provided] to the input [input provided]; see: unicodeTokens @throws use yy instead of YY for formatting years using [format provided] to the input [input provided]; see: unicodeTokens @throws use d instead of D for formatting days of the month using [format provided] to the input [input provided]; see: unicodeTokens @throws use dd instead of DD for formatting days of the month using [format provided] to the input [input provided]; see: unicodeTokens @throws format string contains an unescaped latin alphabet character

@example // Represent 11 February 2014 in middle-endian format: const result = format(new Date(2014, 1, 11), 'MM/dd/yyyy') //=> '02/11/2014'

@example // Represent 2 July 2014 in Esperanto: import { eoLocale } from 'date-fns/locale/eo' const result = format(new Date(2014, 6, 2), "do 'de' MMMM yyyy", { locale: eoLocale }) //=> '2-a de julio 2014'

@example

// Escape string by single quote characters:
const result = format(new Date(2014, 6, 2, 15), "h 'o''clock'")
//=> "3 o'clock"

License

Specify your project's license here, if applicable.

Deployment

Include additional sections if necessary, detailing deployment processes, additional configurations, or contributions guidelines, depending on the complexity and usage of your project.


Keywords

FAQs

Package last updated on 29 Apr 2024

Did you know?

Socket

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Install

Related posts

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc