• Stars
    star
    480
  • Rank 91,562 (Top 2 %)
  • Language
    TypeScript
  • License
    MIT License
  • Created over 4 years ago
  • Updated over 1 year ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

⏰ Blazing fast & lightweight (157 bytes) date formatting for Node.js and the browser.

Light Date

Blazing fast & lightweight (180 bytes) date formatting for Node.js and the browser.

Build Status Coverage Status XO code style minified size

This module aims to provide super fast and easy way to format dates, while also staying lightweight.


Highlights

  • Small. 174 bytes (minified and gzipped). No dependencies. Size Limit controls the size.
  • Fast. See the benchmarks.
  • Compliant. Follows Unicode Technical Standard #35.
  • Well tested. To make sure it handles various use cases correctly.
  • Portable. Works pretty much everywhere.
  • Written in TypeScript.

Install

$ npm install light-date

Usage

import {format} from 'light-date';

const date = new Date('5/1/2020, 4:30:09 PM');

format(date, 'The date is {MM}/{dd}/{yyyy}!'); //=> 'The date is 05/01/2020!'

API

format(date, exp)

Returns a string with formatted date.

date

Type: Date

Date object, which should be used.

exp

Type: string

String, which you want to format, for example: {yyyy}-{MM}-{dd} or Current time: {hh}:{mm}:{ss}.

localeFormat(date, exp, locale?)

Returns a string with formatted date. Uses Intl.DateTimeFormat() for locale-based formatting.

date

Type: Date

Date object, which should be used.

exp

Type: string

String, which you want to format, for example: {EEE} or Era: {GGG}.

locale

Type: string | string[]
Default: 'en-US'

Locale(s), which will be used for formatting.

Patterns

Format of the string is based on Unicode Technical Standard #35.

format

Use this API for simple, most common formatting:

Unit Pattern Result examples
Calendar year {yy} 44, 01, 00, 17
{yyyy} 0044, 0001, 1900, 2020
Month {MM} 01, 02, ..., 12
Day {dd} 01, 02, ..., 31
Hour {HH} 00, 01, 02, ..., 23
Minute {mm} 00, 01, ..., 59
Second {ss} 00, 01, ..., 59
Millisecond {SSS} 000, 0001, ..., 999
localeFormat

Use this API for locale-based formatting:

Unit Pattern Result examples
Month {MMM} Jan, Feb, ..., Dec
{MMMM} January, February, ..., December
{MMMMM} J, F, ..., D
Day of week {E..EEE} Mon, Tue, Wed, ..., Sun
{EEEE} Monday, Tuesday, ..., Sunday
{EEEEE} M, T, W, T, F, S, S

Benchmarks

# Node.js v12.18.3

light-date             x   1,465,394 ops/sec ±0.17% (96 runs sampled)
date-format            x   835,649 ops/sec ±0.20% (96 runs sampled)
moment                 x   650,721 ops/sec ±2.13% (90 runs sampled)
date-fns lightFormat   x   459,170 ops/sec ±0.19% (97 runs sampled)
date-fns format        x   345,845 ops/sec ±4.30% (90 runs sampled)
dayjs                  x   281,183 ops/sec ±0.57% (96 runs sampled)

FAQ

How to use format and localeFormat on one string?
import {format, localeFormat} from 'light-date';

const date = new Date();

format(date, `Current date: ${localeFormat(date, '{MMMM}')} {dd}, {yyyy}`);
How to escape pattern-reserved sequences?

Add a backslash before the opening curly bracket:

import {format} from 'light-date';

format(new Date(), "I'm escaped: \\{yyyy} but I'm not: {yyyy}");
//=> "I'm espaced: {yyyy} but I'm not: 2020"

To avoid having to escape backslashes, use String.raw:

format(new Date(), String.raw`I'm escaped: \{yyyy} but I'm not: {yyyy}`;
//=> "I'm espaced: {yyyy} but I'm not: 2020"
Why doesn't localeFormat work correctly with some locales in Node?

Before version 13, Node is shipped with limited ICU data (= localization data). Because of this, using certain locales with localeFormat may produce incorrect results in Node up to version 12.

You can either use Node 13+ or install full ICU data manually:

  1. npm install --save cross-env full-icu

  2. Update the scripts section of package.json to set the environment variable NODE_ICU_DATA. For example:

    {
      "scripts": {
        // Before
        "start": "index.js",
        "test":  "react-scripts test",
    
        // After
        "start": "cross-env NODE_ICU_DATA=node_modules/full-icu index.js",
        "test":  "cross-env NODE_ICU_DATA=node_modules/full-icu react-scripts test"
      }
    }

    This way, when you run npm start or npm test, Node will load the full ICU data from node_modules/full-icu, and you should get correctly formatted results.

    The cross-env package is needed to support setting environment variables on Windows.

License

MIT © Antoni Kepinski

More Repositories

1

oji

(◕‿◕) Text Emoticons Maker
JavaScript
702
star
2

styled-react-boilerplate

Minimal & Modern boilerplate for building apps with React & styled-components
JavaScript
208
star
3

cash-cli

💰💰 Convert currency rates directly from your terminal!
JavaScript
202
star
4

awesome-calculators

😎 A curated list of resources related to calculators!
126
star
5

xa

Beautiful & Customizable logger ❤️
TypeScript
81
star
6

nasa-cli

🚀 Download NASA Picture of the Day from your terminal!
JavaScript
69
star
7

pizza-cli

🍕 Order a pizza in a CLI app (just for fun!)
JavaScript
60
star
8

speedo-cli

⌚️ Internet speed report in your terminal!
JavaScript
56
star
9

bitly-cli-client

🔪 Shorten links with Bitly in your terminal!
JavaScript
47
star
10

omdb-graphql-wrapper

🚀 GraphQL wrapper for the OMDb API
JavaScript
44
star
11

fastic

🚀 Fast & Lightweight CLI HTTP server
JavaScript
41
star
12

deepin-snazzy

Elegant Deepin Terminal theme with bright colors.
Shell
39
star
13

static-webpack-boilerplate

🚀 Minimal & Modern Webpack Boilerplate for building static sites
JavaScript
39
star
14

odc

📦 Update npm dependencies easily!
JavaScript
31
star
15

timestampy

🕒 Bunch of utilities useful when working with UNIX timestamps
TypeScript
20
star
16

currency-converter

💰 Easily convert between 32 currencies
TypeScript
17
star
17

attoid

Secure URL-friendly unique string ID generator in <8 LOC
TypeScript
16
star
18

status-git

🐙 CLI for checking Github status
JavaScript
13
star
19

archfetch

🖼️ Simple CLI system information tool for Arch Linux.
Shell
11
star
20

movies-cli

🎥 Get information about your favorite movies
JavaScript
10
star
21

site

My personal one page website
CSS
10
star
22

minifly

🗜️ Minify different types of files easily
JavaScript
9
star
23

open-weather-cli

⛅ CLI for fetching weather forecast using openweathermap api
JavaScript
9
star
24

is-dnt

🕵️ Check whether the Do not track (DNT) policy is enabled in user's browser or not
TypeScript
7
star
25

alpha

Static Website Theme, also my old website source :) NEW WEBSITE SOURCE -->
HTML
7
star
26

quick-air

☁️ Check air quality near you quickly, using Airly API
JavaScript
6
star
27

rubiks

Rubik's Cube implementation in TypeScript
TypeScript
5
star
28

airly-cli

Get the latest info about air pollution in Poland ☁️
JavaScript
5
star
29

mija

☢️ Console Logger with Emoji support!
TypeScript
5
star
30

dotfiles

🔮 Backup of my settings and preferences
Shell
4
star
31

air-radar

Generate air quality reports from anywhere in the world and share them with your friends!
TypeScript
4
star
32

discord-bot

Discord bot for Polish Electron Community server.
JavaScript
4
star
33

cpp

Collection of C++ scripts I made during Computer Science classes
C++
4
star
34

onion-omega2-coronavirus-oled

Display coronavirus stats on the Omega Onion 2 OLED Extension
JavaScript
4
star
35

maintaining-big-open-source-project

My presentation for the Hacktoberfest 2019 Meetup in Poznan
JavaScript
4
star
36

ing-autofill

Make password managers autofill the masked password on ING bank's website automagically.
JavaScript
3
star
37

pesel-utils

Bunch of utilities useful when working with PESEL numbers
TypeScript
3
star
38

kolberg

🔍 Useful utilities for string searching and manipulation.
TypeScript
3
star
39

prasowka-generator

WIP
JavaScript
3
star
40

welding-utils

🛠️ Useful utilities related to welding
TypeScript
2
star
41

parsify-plugin-covid19

Parsify plugin, that adds COVID 19-related variables 🦠
TypeScript
2
star
42

rpi-unicorn-phat

Playing with Raspberry Pi and Pimoroni Unicorn pHAT 🦄
JavaScript
2
star
43

xxczaki

2
star
44

storage-async

(WIP) Lightweight, asynchronous and atomic key-value JSON storage for Node.js applications. Supports TTL.
TypeScript
2
star
45

ship-classifier

Classify ship types using machine learning (beta)
JavaScript
2
star
46

notes

Recruitment task
TypeScript
2
star
47

cashify-rs

Lightweight currency conversion library, written in Rust.
Rust
2
star
48

password-encrypt

Small Windows tool to encrypt passwords in MD5!
C#
1
star
49

universal-calc-and-conv

Universal Calculator and Converter in one app!
Java
1
star
50

online-badges

All the badges in one place!
1
star
51

universal

Universal node-fetch wrapper
JavaScript
1
star
52

privacy-policy

Privacy Policy for my apps etc.
1
star
53

assets

1
star
54

tsconfig

Shared TypeScript config for my projects
1
star
55

welding-toolbox

An app containing a set of useful welding tools 🛠️
JavaScript
1
star
56

welding-toolbox-2

An app containing a set of useful welding tools, written in React Native ⚛️
JavaScript
1
star
57

ubufetch

🖼️ Simple CLI system information tool for Linux Ubuntu.
Shell
1
star
58

archlabs-setup

Simple script for basic archlabs setup
Shell
1
star