⚡️ Fast parsing, formatting and timezone manipulations for dates

Overview

node-cctz Build Status

CCTZ is a C++ library for translating between absolute and civil times using the rules of a time zone.

Install

You will need C++11 compatible compiler to build this binding. For most systems this will work:

$ npm install --save cctz

If you have Ubuntu 12.04, then install clang-3.4 and set-up environment:

$ sudo apt-get install clang-3.4
$ export CXX=clang++
$ export npm_config_clang=1

Usage

const {convert, format, CivilTime} = require('cctz');

const unix = convert(new CivilTime(2015, 9, 22, 9), 'America/Los_Angeles');
console.log(format('Talk starts at %T %z (%Z)', unix, 'America/New_York'));

// => Talk starts at 12:00:00 -0400 (EDT)

API

convert(time, timezone)

Converts CivilTime to unix timestamp and vice versa.

time

Type: CivilTime or number

If time is CivilTime, then method returns Unix timestamp (without fractional part). Otherwise returns CivilTime.

timezone

Type: TimeZone or string

TimeZone objcet, that represents target timezone for converting.

format(format, unix, [timezone])

Returns formatted unix timestamp according to timezone.

format

Type: string

Format of output. See strftime documentation and Google CCTZ sources for syntax.

unix

Type: number

Unix timestamp in seconds (can have fractional part).

timezone

Type: TimeZone or string Default: local timezone

TimeZone objcet, that represents target timezone for formatting.

parse(format, input, [timezone])

Parses input string according to format string (assuming input in timezone).

Returns unix timestamp or undefined if parsing failed.

format

Type: string

Format of input argument. See strftime documentation and Google CCTZ sources for syntax.

input

Type: string

Input string to parse.

timezone

Type: TimeZone or string
Default: Timezone from input or local timezone

Timezone, that should be used in parse. Timezone can be part of input:

cctz.parse('%Y-%m-%d %H:%M:%S %Ez', '2015-09-22 09:35:12+03:00');

tz(name)

Alias for cctz.load_time_zone

Use this method instead new TimeZone – because it caches TimeZone objects inside.

Returns TimeZone object.

name

Type: string

Timezone name, that should be loaded from /usr/share/zoneinfo.

now()

Alias for Math.floor(Date.now() / 1000)

Returns unix timestamp in seconds. All methods can accept timestamp with fractional milliseconds (if you need such accuracy).

CivilTime

Holder for cctz::civil_second with getters and setters for properties.

CivilTime(year = 1970, month = 1, day = 1, hour = 0, minute = 0, second = 0)

Creates CivilTime object with next properties:

  • year – getter and setter
  • month – getter and setter [1:12]
  • day – getter and setter [1:31]
  • hour – getter and setter [0:23]
  • minute – getter and setter [0:59]
  • second – getter and setter [0:59]
  • yearday – only getter [1:356]
  • weekday – only getter [0:6]

Tip: Fastest way to add amount of time is to add number of seconds to unix timestamp.

CivilTime.startOfYear()

Returns new CivilTime object with start of year.

CivilTime.startOfMonth()

Returns new CivilTime object with start of month.

CivilTime.startOfDay()

Returns new CivilTime object with start of day.

CivilTime.startOfHour()

Returns new CivilTime object with start of hour.

CivilTime.clone()

Returns cloned CivilTime object.

TimeZone

Holder for cctz::time_zone.

TimeZone(name)

Creates new object with TimeZone.

TimeZone.lookup(unix)

Returns cctz::absolute_lookup object.

TimeZone.lookup(civiltime)

Returns cctz::civil_lookup object.

TimeZone.name

Name of TimeZone.

Benchmarks

Format              (cctz) x 532,683 ops/sec ±2.80% (78 runs sampled)
                    (Date) x 191,400 ops/sec ±2.59% (81 runs sampled)
                (date-fns) x  91,772 ops/sec ±1.58% (85 runs sampled)
                  (moment) x  56,508 ops/sec ±6.35% (76 runs sampled)

Parse               (cctz) x 1,105,353 ops/sec ±0.59% (86 runs sampled)
                    (Date) x 1,200,218 ops/sec ±2.00% (82 runs sampled)
                (date-fns) x   249,225 ops/sec ±5.00% (77 runs sampled)
                  (moment) x    23,905 ops/sec ±1.91% (80 runs sampled)

Add hour            (cctz) x 6,123,083 ops/sec ±5.39% (82 runs sampled)
                    (Date) x 3,604,915 ops/sec ±1.13% (69 runs sampled)
                (date-fns) x 3,211,900 ops/sec ±2.28% (81 runs sampled)
                  (moment) x   590,854 ops/sec ±8.48% (72 runs sampled)

Convert Ut->Time    (cctz) x 653,305 ops/sec ±9.33% (68 runs sampled)
                  (moment) x 144,580 ops/sec ±2.18% (83 runs sampled)

Convert Time->Ut    (cctz) x 987,437 ops/sec ±11.68% (70 runs sampled)
                  (moment) x 154,492 ops/sec ±3.54% (82 runs sampled)

Run npm i and then npm run bench.

License

MIT © Vsevolod Strukchinsky

You might also like...

Vanillajs-datepicker - A vanilla JavaScript remake of bootstrap-datepicker for Bulma and other CSS frameworks

Vanilla JS Datepicker A vanilla JavaScript remake of bootstrap-datepicker for Bulma and other CSS frameworks This package is written from scratch as E

Dec 30, 2022

CalendarPickerJS - A minimalistic and modern date-picker component/library 🗓️👨🏽‍💻 Written in Vanilla JS

CalendarPickerJS The simple and pretty way to let a user select a day! Supports all major browser. Entirely written in Vanilla JavaScript with no depe

Dec 6, 2022

Simple drag and drop with dragula

Simple drag and drop with dragula

Drag and drop so simple it hurts Official Angular wrapper for dragula. Notice: v2 has been released It contains a number of breaking changes. Follow t

Dec 18, 2022

Create Persian Calendar as html helper with tag builder c# , and convert selected persian date to gregorian date

Create Persian Calendar as html helper with tag builder c# , and convert selected persian date to gregorian date

Persian-Calendar Use JS,Html,CSS,C# White theme for Persian Calendar , easy to use. Create Persian Calendar as html helper. Use Tag builder in c# for

Feb 28, 2022

A date picker web component, and spiritual successor to duet date picker

date-picker A date picker web component, based on duet date picker, except authored with Lit and using shadow DOM. This is a work in progress. Todo:

Aug 3, 2022

DEPRECATED: Timezone-enabled JavaScript Date object. Uses Olson zoneinfo files for timezone data.

TimezoneJS.Date A timezone-enabled, drop-in replacement for the stock JavaScript Date. The timezoneJS.Date object is API-compatible with JS Date, with

Nov 20, 2022

Nodeparse - A lightweight, vanilla replacement for Express framework when parsing the HTTP body's data or parsing the URL parameters and queries with NodeJS.

Nodeparse - A lightweight, vanilla replacement for Express framework when parsing the HTTP body's data or parsing the URL parameters and queries with NodeJS.

nodeparse A lightweight, vanilla replacement for Express framework when parsing the HTTP body's data or parsing the URL parameters and queries with No

Jan 8, 2022

Lightweight and simple JS date formatting and parsing

fecha Lightweight date formatting and parsing (~2KB). Meant to replace parsing and formatting functionality of moment.js. NPM npm install fecha --save

Jan 5, 2023

Tiny JavaScript library (1kB) by CurrencyRate.today, providing simple way and advanced number, money and currency formatting and removes all formatting/cruft and returns the raw float value.

Zero dependency tiny JavaScript library (1kB bytes) by CurrencyRate.today, providing simple way and advanced number, money and currency formatting and removes all formatting/cruft and returns the raw float value.

Nov 8, 2022

A string of four operations of the library, can solve the js digital calculation accuracy of scientific notation and formatting problems, support for thousands of decimal point formatting output operations

A string of four operations of the library, can solve the js digital calculation accuracy of scientific notation and formatting problems, support for thousands of decimal point formatting output operations

Apr 6, 2022

👑 A tiny yet powerful tool for high-performance color manipulations and conversions

👑 A tiny yet powerful tool for high-performance color manipulations and conversions

Colord is a tiny yet powerful tool for high-performance color manipulations and conversions. Features 📦 Small: Just 1.7 KB gzipped (3x+ lighter than

Jan 3, 2023

JavaScript library for all kinds of color manipulations

Chroma.js Chroma.js is a tiny small-ish zero-dependency JavaScript library (13.5kB) for all kinds of color conversions and color scales. Usage Initiat

Jan 4, 2023

Grupprojekt för kurserna 'Javascript med Ramverk' och 'Agil Utveckling'

JavaScript-med-Ramverk-Laboration-3 Grupprojektet för kurserna Javascript med Ramverk och Agil Utveckling. Utvecklingsguide För information om hur utv

May 18, 2022

Hemsida för personer i Sverige som kan och vill erbjuda boende till människor på flykt

Getting Started with Create React App This project was bootstrapped with Create React App. Available Scripts In the project directory, you can run: np

May 3, 2022

Kurs-repo för kursen Webbserver och Databaser

Webbserver och databaser This repository is meant for CME students to access exercises and codealongs that happen throughout the course. I hope you wi

Jan 3, 2023

A lightweight javascript timezone library

A lightweight javascript timezone library

Isn't it weird how we can do math in our head, but not date math? how many days until the end of the year? what time was it, 11 hours ago? is it lunch

Dec 29, 2022

Timezone support for moment.js

Moment Timezone IANA Time zone support for Moment.js Project Status Moment-Timezone is an add-on for Moment.js. Both are considered legacy projects, n

Jan 1, 2023

💠 Webapp to see what time is in any timezone

Timero Webapp to see what time is in any timezone. Deploy https://ultirequiem.github.io/timero Characteristic Responsive Design Uses Packup as Bundler

May 15, 2022

Minimal utility to convert to or from any timezone. Deno/Node/Browser. ESM/CommonJS.

minitz Features Convert dates between any timezone supported by the system. Parses ISO8601 time strings. MIT licensed, use the library any way you wan

Oct 10, 2022
Comments
  • Floor timestamp from cctz.now()

    Floor timestamp from cctz.now()

    Improvement for #13.

    Flooring is not expensive operation:

    Floating x 10,478,063 ops/sec ±0.89% (84 runs sampled)
    Floor x 10,028,852 ops/sec ±1.89% (84 runs sampled)
    

    //cc @maxvipon

    opened by floatdrop 1
  • Accept timezone as string

    Accept timezone as string

    This gives no significant performance boost, but code will a little bit cleaner. For example:

    import {CivilTime, convert, tz} from 'cctz';
    
    convert(new CivilTime(2015, 9, 22, 9), tz('America/Los_Angeles'));
    // vs
    convert(new CivilTime(2015, 9, 22, 9), 'America/Los_Angeles');
    
    enhancement 
    opened by floatdrop 0
  • Civil type

    Civil type

    Since JavaScript does not have type conversions, there is no need for different types for civil time.

    • [x] Replace CivilSecond with CivilTime
    • [x] Add clone method
    • [x] Add startOf/endOf methods to match cctz::civil_* types.
    enhancement 
    opened by floatdrop 0
  • Accept CivilTime as array

    Accept CivilTime as array

    Same simplification as #10:

    cctz.convert(new cctz.CivilTime(2015, 9, 22, 9), 'America/Los_Angeles');
    vs
    cctz.convert([2015, 9, 22, 9], 'America/Los_Angeles');
    
    enhancement help wanted 
    opened by floatdrop 0
Owner
Vsevolod Strukchinsky
Vsevolod Strukchinsky
Lightweight and simple JS date formatting and parsing

fecha Lightweight date formatting and parsing (~2KB). Meant to replace parsing and formatting functionality of moment.js. NPM npm install fecha --save

Taylor Hakes 2k Jan 5, 2023
A lightweight javascript timezone library

Isn't it weird how we can do math in our head, but not date math? how many days until the end of the year? what time was it, 11 hours ago? is it lunch

spencer kelly 3.7k Dec 29, 2022
Timezone support for moment.js

Moment Timezone IANA Time zone support for Moment.js Project Status Moment-Timezone is an add-on for Moment.js. Both are considered legacy projects, n

Moment.js 3.7k Jan 1, 2023
Parse, validate, manipulate, and display dates in javascript.

Moment.js A JavaScript date library for parsing, validating, manipulating, and formatting dates. Project Status Moment.js is a legacy project, now in

Moment.js 47.1k Jan 2, 2023
⏱ A library for working with dates and times in JS

Luxon Luxon is a library for working with dates and times in JavaScript. DateTime.now().setZone("America/New_York").minus({ weeks: 1 }).endOf("day").t

Moment.js 13.4k Jan 9, 2023
A tiny and fast zero-dependency date-picker built with vanilla Javascript and CSS.

A tiny zero-dependency and framework-agnostic date picker that is incredibly easy to use! Compatible with any web UI framework, vanilla JS projects, and even HTML-only projects!

Nezar 1 Jan 22, 2021
This library provide a fast and easy way to work with date.

Calendar.js Calendar.js provide a fast way to work with dates when you don't wanna deal with hours, minute, second and so on. It means that Calendar.j

ActuallyNotaDev 3 Apr 27, 2022
jQuery plugin to allow dragging and dropping of elements and sorting of lists and other nested structures.

Drag and Drop Basic jQuery plugin to allow drag and drop: dragging dropping of dragged elements sorting of lists and other nested html structures (ul,

Ole Trenner 12 Aug 26, 2021
A simple and reusable datepicker component for React

React Date Picker A simple and reusable Datepicker component for React (Demo) Installation The package can be installed via npm: npm install react-dat

HackerOne 7k Jan 4, 2023
🕑 js-joda is an immutable date and time library for JavaScript.

js-joda is an immutable date and time library for JavaScript. It provides a simple, domain-driven and clean API based on the ISO8601 calendar.

null 1.5k Dec 27, 2022