GithubHelp home page GithubHelp logo

light-date's Introduction

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.

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

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

light-date's People

Contributors

xxczaki avatar mtsknn avatar broofa avatar

Stargazers

wgnr avatar luk avatar  avatar  avatar Justin Godesky avatar Andrei Cristea avatar simon avatar Bhanu Teja Pachipulusu avatar Artur Dudek avatar Ciro Lo Sapio avatar Jeff Galbraith avatar Greg W avatar Alex Younger avatar Sadegh Barati avatar  avatar Van Thong Le avatar KarlitosD avatar  avatar Knut Kirkhorn avatar  avatar Sinan Taga avatar Max Duval avatar  avatar  avatar Eric Bailey avatar Andrés Brugarolas avatar ​Faizaan avatar Wojciech Pasiński avatar Giavinh avatar Mustafa YUMURTACI avatar Burak Sonmez avatar Travis van der F. avatar Uğur Oruç avatar Yegor avatar 麦子 avatar Takuya Fukuju avatar David Dias avatar yofri avatar Vlad Vaviloff avatar  avatar Pedro Duarte avatar Dana Woodman avatar Andrii Oriekhov avatar kosl90 avatar Wayne avatar KeiSei avatar  avatar Ivan Malopinsky avatar Kyriakos-Ioannis D. Kyriakou avatar  avatar Darenome avatar Christopher Fouquier avatar Alex Matias avatar  avatar Michael Braunegger avatar  avatar Christian Kaatz avatar Nick Cairns avatar Uladzimir avatar Andrew Miller avatar Jan Vlnas avatar  avatar Arley Lobato avatar wmalgoire avatar Ville Lautanala avatar  avatar Pierrick Turelier avatar Rajkumar Singh avatar Eduardo Lavaque avatar masx200 avatar  avatar  avatar Garrett Nay avatar Fazal avatar  avatar Khodor Ammar avatar Gray Zhang avatar Andres Valderrama Barbosa avatar  avatar Chris Marshall avatar Henrik Hansson avatar Nobutaka OSHIRO avatar George Mandis avatar Andrew Carpenter avatar Pedro Henrique Lemes Da Silva avatar Ahmet Abdulrahman . Señor developer avatar Stefan Bauckmeier avatar vincentYang avatar Arjun Nayak avatar Arturo Mackimmie avatar rix1 avatar Konstantin Knyazev avatar  avatar Jesús Rubio avatar Paul Dalton avatar  avatar Johan Satgé avatar Jayce Zhang avatar Selwyn avatar Rubén Moya avatar

Watchers

Stig Kleppe-Jørgensen avatar evandrix avatar James Cloos avatar  avatar Alexey Lyakhov avatar  avatar  avatar Alex Matias avatar

light-date's Issues

Add escape mechanism

Ideally, it would be an opt-in feature, which would allow writing pattern-reserved sequences (such as {mm} or {EEE}) without them being formatted. Not all date formatting libraries provide this feature as it's relatively unlikely that one would like to write something like {mm}, but it would be nice to have.

We could allow escape through single quotes, like so:

import {format} from 'light-date';

format(new Date(), `Current date is: {yyyy}/{MM}/{dd} (using '{yyyy}/{MM}/{dd}' format)`);
//                                                            ~~~~~~~~~~~~~~~~
//                                                              the following would not be formatted.

Solutions, which I think are worth thinking about:

  1. Regular expression change(s)
  2. tagged string template, like:
escape`{yyyy}/{MM}/{dd}`

Add ability to format with a specific timezone

Hi, we are looking for a simple formatting library to format dates and times in templates on the server, but using the timezone the clients sends us. I can't seem to find settings for timezone in this library, so are they missing, or isn't it documented, or maybe I'm looking over it? If this is missing, it would be nice if this can be added.

am/pm

{H} {TT} => "5 AM"

lightFormat ==> localeFormat typo?

In the FAQ example:

import {format, lightFormat} from 'light-date';

But I think you meant this:

import {format, localeFormat} from 'light-date';

?

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.