• Stars
    star
    222
  • Rank 179,123 (Top 4 %)
  • Language
    TypeScript
  • License
    BSD 3-Clause "New...
  • Created almost 2 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

a compact calendar date

cdate - a compact calendar date

Node.js CI npm version gzip size

  • Fast: the benchmark result shows that cdate is 37% faster than Moment.js, Day.js and Luxon
  • Display: Moment.js-style .format("YYYY-MM-DD HH:mm:ss")
  • Developer friendly display: strftime-style .text("%Y-%m-%d %H:%M:%S")
  • Manipulation: .add(1, "month").startOf("week").endOf("day") like Moment.js does but immutable
  • Time zones: names like America/New_York supported by Intl.DateTimeFormat API as well as UTC offset like GMT-05:00
  • I18N: .locale("fr").text("%c") results dim. 2 janv. 2022, 03:04:05 also managed by Intl API
  • Small: 9KB minified and less than 4KB gzip including time zones supported per default
  • Fully immutable: even plugins never effect the cdate's core. None of "dual package hazard"
  • Pure ESM, CommonJS - Node.js, Browsers, TypeScript

SYNOPSIS

// ESM
import {cdate} from "cdate";

// CommonJS
const {cdate} = require("cdate");

Display:

const now = cdate();

console.log(now.format("YYYY-MM-DD HH:mm:ss.SSSZ"));

console.log(now.text("%Y-%m-%d %H:%M:%S.%L%:z"));

Get + Set:

const isLeapYear = (year) => {
    return cdate().set("year", year).set("month", 1).endOf("month").get("date") === 29;
}

isLeapYear(2020); // => true
isLeapYear(2021); // => false
isLeapYear(2022); // => false
isLeapYear(2023); // => false
isLeapYear(2024); // => true

Manipulation:

const today = cdate("2023-01-01");
console.log(today.format("   MMMM YYYY"));

const start = today.startOf("month").startOf("week");
const end = today.endOf("month").endOf("week");

for (let day = start; +day < +end;) {
    const week = [];
    for (let i = 0; i < 7; i++) {
        week.push(day.format("DD"))
        day = day.next("day");
    }
    console.log(week.join(" "));
}

Result:

   January 2023
01 02 03 04 05 06 07
08 09 10 11 12 13 14
15 16 17 18 19 20 21
22 23 24 25 26 27 28
29 30 31 01 02 03 04

TYPESCRIPT

See TypeScript declaration index.d.ts for detail. API may change.

BENCHMARK

The result shows that cdate is 37% faster than moment!

Library Version Minified Size Local Time Bench Time Zone Bench Note
cdate 0.0.5 9 KB 7,868 ops/sec 6,471 ops/sec fastest! 🍺
moment 2.29.4 100 KB+ 5,744 ops/sec 3,622 ops/sec big tz database
dayjs 1.11.7 13 KB 3,875 ops/sec 89 ops/sec DST related bugs
luxon 3.3.0 74 KB 930 ops/sec 158 ops/sec different API

Tested on node v18.14.2, Apple Silicon M1, MacBook Pro. "Minified Size" for dayjs includes its utc and time zone plugins. Each 1 op above includes:

  • 192 ops of .add() manipulations
  • 60 ops of .startOf() and .endOf()
  • 30 ops of .format() displaying

Try the benchmark on your environment:

git clone --depth=1 https://github.com/kawanet/cdate.git
cd cdate
npm install
npm run build
node cli/benchmark.js

PLUGIN SYSTEM

To be minimal, the cdate itself has many missing features compared to Moment.js's gorgeous APIs. If you need subtract() method, for example, you can add it with your own plugin:

const cdateS = cdate().plugin(P => class extends P {
    subtract(diff, unit) {
        return this.add(-diff, unit);
    }
}).cdateFn();

cdateS("2023-01-01").subtract(1, "day").format("YYYY-MM-DD");
// => '2022-12-31'

Or just call add() method simply with a negative value:

cdate("2023-01-01").add(-1, "day").format("YYYY-MM-DD");
// => '2022-12-31'

Note that the subtract() method implemented above is available only for instances created by cdateS() function, as the cdate's plugin system is immutable as well.

LOCALES

It supports English names: December, Sunday, etc., per default. There are ways to change it. The most simple way is to call .locale() method which enables I18N via Intl API on demand:

// English per default
cdate().format("ddd D MMM");
// => 'Sun 18 Dec'

cdate().locale("de").format("ddd D MMM");
// => 'So 18 Dez'

If you still need to support old environments which does not have Intl API, try cdate-locale which has a series of locale settings prebuilt via Intl API.

const {locale_de} = require("cdate-locale/locale/de.js");
cdate().handler(locale_de).format("ddd D MMM");
// => 'So 18 Dez'

The last way is for you to code it. Call .handler() method to customize handlers for .format() specifiers:

const weekday = ["So", "Mo", "Di", "Mi", "Do", "Fr", "Sa"];
const month = ["Jan", "Feb", "Mär", "Apr", "Mai", "Jun", "Jul", "Aug", "Sep", "Okt", "Nov", "Dez"];
const cdateDE = cdate().handler({
    ddd: (dt) => weekday[dt.getDay()],
    MMM: (dt) => month[dt.getMonth()],
}).cdateFn();

cdateDE().format("ddd D MMM");
// => 'So 18 Dez'

If you prefer strftime-style, the same .handler() method also works for .text() specifiers:

const cdateDE = cdate().handler({
    "%a": (dt) => weekday[dt.getDay()],
    "%b": (dt) => month[dt.getMonth()],
}).cdateFn();

cdateDE().text("%a %-d %b");
// => 'So 18 Dez'

TIMEZONES

It supports both UTC offset and timezone names without any external modules and plugins. If you use Japan Standard Time (JST) GMT+09:00 for instance:

const dt = new Date("2023-01-01T00:00:00+09:00");

cdate(dt).utcOffset(+9).text(); // +9 hours

cdate(dt).utcOffset(+540).text(); // +540 minutes

cdate(dt).utcOffset("+09:00").text();

cdate(dt).utcOffset("GMT+09:00").text();

cdate(dt).tz("Asia/Tokyo").text();
// => '2023-01-01T00:00:00.000+09:00'

If your app is designed to use a constant UTC offset value, call like .utcOffset(+9).cdateFn() to preset the offset. It runs faster.

const cdateJST = cdate().utcOffset(+9).cdateFn();

cdateJST(dt).text(); // fast

LINKS

More Repositories

1

msgpack-lite

Fast Pure JavaScript MessagePack Encoder and Decoder / msgpack.org[JavaScript]
JavaScript
990
star
2

int64-buffer

64bit Long Integer on Buffer/ArrayBuffer in Pure JavaScript
JavaScript
78
star
3

event-lite

event-lite.js - Light-weight EventEmitter (less than 1KB when minified)
JavaScript
54
star
4

nginx-forward-proxy

forward proxy configuration for nginx
Shell
39
star
5

from-xml

fromXML - Pure JavaScript XML Parser
JavaScript
36
star
6

KWFontPicker

Font Picker Library for iPhone/iOS Devices
Objective-C
30
star
7

sha256-uint8array

Fast SHA-256 digest hash based on Uint8Array, pure JavaScript.
TypeScript
19
star
8

electron-express

Electron + Express + WebSocket + msgpack (Sample Application)
JavaScript
17
star
9

social-library-ios5

Social Library for iOS5
15
star
10

obop

MongoDB-style object operators makes array manipulation easy: where/order/update/view
JavaScript
12
star
11

timestamp-nano

Timestamp for 64-bit time_t, nanosecond precision and strftime
JavaScript
10
star
12

express-intercept

Build Express middleware to intercept / replace / inspect / transform response
TypeScript
9
star
13

msgpack-test-suite

a dataset for testing magpack library
JavaScript
9
star
14

to-xml

toXML - Pure JavaScript XML Writer
JavaScript
9
star
15

OCSS

OCSS - CSS Parser for iOS
CSS
8
star
16

sed-lite

`sed` compiler for JavaScript
TypeScript
7
star
17

iconv-cp932

encodeURIComponent for CP932 (Shift_JIS)
TypeScript
7
star
18

jaccard-index

Promise-based Jaccard similarity coefficient index matrix calculation
JavaScript
6
star
19

sha1-uint8array

Fast SHA-1 digest hash based on Uint8Array, pure JavaScript.
TypeScript
6
star
20

jp-zipcode-lookup

Japan Postal Zip Code Lookup
TypeScript
5
star
21

process.argv

light-weight command line arguments parser for cli application
JavaScript
5
star
22

qs-lite

Lightweight querystring parse() & stringify() at less than 1KB minified
JavaScript
5
star
23

createhash-browser

SubtleCrypto.digest() shim
TypeScript
4
star
24

msgpack-ts

TypeScript msgpack encoder and decoder
JavaScript
4
star
25

rdotjson

Android String Resource XML Parser
JavaScript
4
star
26

HTML-TagParser

Yet another HTML document parser with DOM-like methods
Perl
4
star
27

XML-TreePP

XML::TreePP -- Pure Perl implementation for parsing/writing XML documents
Perl
4
star
28

jp-pref-lookup

Japan Prefecture Code Lookup / 10km mesh reverse geocoding
TypeScript
4
star
29

key-value-compress

Key-Value storage interceptor to serialize, deserialize, deflate, inflate, split, concatenate content.
TypeScript
3
star
30

msgpack-websocket

msgpack on WebSocket
JavaScript
3
star
31

jp-city-lookup

Japan City Code Lookup / 1km mesh reverse geocoding
TypeScript
3
star
32

Lingua-KO-Romanize-Hangul

Romanization of Korean language
Perl
3
star
33

kagodb

Kago Database Engine
JavaScript
3
star
34

menge

Minimalist set theory operations for Array-like objects in less than 1KB
JavaScript
3
star
35

buffer.min.js

Minified standalone buffer module from node.js, for the browser.
HTML
2
star
36

rdotswift

res/values/strings.xml to R.swift
JavaScript
2
star
37

Plack-Response-Data

Response Content Body Encoder for JSON, XML, YAML, etc.
Perl
2
star
38

sql-statement

Tiny SQL Statement Builder
TypeScript
2
star
39

ipa-dl

an web page for downloading .ipa file
HTML
2
star
40

as3kawalib

ActionScript Kawanet Library
JavaScript
2
star
41

fbgraph-batch

Facebook Graph API Batch Request Client
JavaScript
2
star
42

node-cli-starter

Node.js Starter Kit for CLI
JavaScript
2
star
43

jaccard-stream

Jaccard Similarity Coefficient Index Stream Transform
JavaScript
2
star
44

cdate-moment

moment.js compat plugin for cdate
JavaScript
2
star
45

Lingua-ZH-Romanize-Pinyin

Romanization of Standard Chinese language
Perl
2
star
46

KWImageSprites

KWImageSprites clips sprites from an image like CSS-sprite
Objective-C
1
star
47

test-nginx-express

a minimal sample code for express.js and nginx reverse proxy
JavaScript
1
star
48

japanpost-zipcode

Japan Post Zipcode
TypeScript
1
star
49

weboverlay

Layered Hybrid Web Server: Local, Remote, and Transform
TypeScript
1
star
50

blue-light-fliter

1
star
51

msgpack-test-js

msgpack compatibility test driver
JavaScript
1
star
52

infiniten

A tiny manager for production process running infiniten like forever, nodeman or pm2
Shell
1
star
53

SQL-Pico

SQL-Pico
Perl
1
star
54

KTween

KTween - Simple & Fast Tween Engine for AS3
ActionScript
1
star
55

git-cat-file

Pure JavaScript `git cat-file -p` for node.js
TypeScript
1
star
56

Plack-Middleware-ContentOverride

Override Request Content Body by File Uploading or Query Parameter
Perl
1
star
57

nginx-static-starter

Nginx Static HTTP Server Starter Skeleton
Shell
1
star
58

Encode-JP-Emoji

Encode::JP::Emoji - Emoji encodings and cross-mapping tables in pure Perl
Perl
1
star
59

nginx-cache-proxy

Nginx as a HTTP proxy server with strong caching
Shell
1
star
60

Config-Pico

Config::Pico - Picoscale Perl Interpretative COnfiguration
Perl
1
star
61

kawapp

Kyukou asynchronous Web application framework
JavaScript
1
star
62

misc

Kawanet Misc
Perl
1
star
63

async-cache-queue

Lightweight async task queue with cache, timeout and throttle management
TypeScript
1
star
64

Lingua-JA-Romanize-Japanese

Romanization of Japanese language
Perl
1
star
65

test

Test Repository
1
star
66

middleware-supertest

Testing Express.js RequestHandler middlewares both on server-side and client-side
TypeScript
1
star