A blazing-fast JavaScript date library with intelligent caching, automatic DST detection, and zero-config timezone handling. Perfect for high-performance applications, real-time systems, and data-intensive operations where speed and accuracy matter most.
- β‘ Lightning Fast - Over 40x faster timezone operations than Day.js
- π ~95% Less Time Overall - Fastest in every scenario vs Moment.js, Day.js, and Luxon
- πΎ Memory Efficient - Bounded caches with automatic eviction keep long-running processes stable
- βοΈ Smart Caching - ~30% less time on repeated operations with built-in caching
- π‘οΈ Fail-Fast Design - Invalid dates immediately throw errors, preventing silent bugs in production
- π― Type Safety - Rejects malformed dates instead of returning unexpected results
- β Predictable Behavior - Never continues with invalid dates, unlike libraries that return "Invalid Date"
- π Production Tested - 1,454 tests covering edge cases and DST transitions, with expected values checked against moment, Luxon and
Intl
- π Accurate Timezone Handling - Fast, DST-aware timezone conversions and calendar arithmetic (a day stays a day across DST changes)
- π§ Zero-Config DST - Automatic Daylight Saving Time detection without manual intervention
- π Big Data Ready - Handles 1M-operation workloads efficiently
- π Production Proven - Cross-platform compatibility with zero dependencies
npm install kk-dateformat_c()was removed. Dynamicformat()templates cover every use case in a single call:
// before (v4): date.format_c(' ', 'DD', 'MMMM', 'YYYY')
date.format('DD MMMM YYYY');
// separators that could read as tokens go in [brackets]:
// before (v4): date.format_c('T', 'YYYY-MM-DD', 'HH:mm:ss')
date.format('YYYY-MM-DDTHH:mm:ss');format()now supports the full moment/dayjs display-token vocabulary βYY M Mo Q Qo DDD DDDo DDDD d dd do e E w wo ww W Wo WW gg gggg GG GGGG H h k kk m s S..SSSSSSSSS Z ZZ z zz zzzplus in-templateX/xwere added to the existing 16 tokens. Because many single letters are now significant, unbracketed literal words in templates can change output β bracket literal text ('[Week] w'), exactly as in moment/dayjs. See the supported tokens table.
See the migration guide for details.
const kk_date = require('kk-date');
// Enable caching for high-performance applications
kk_date.caching({ status: true, defaultTtl: 3600 });
// Create and format dates
const date = new kk_date('2024-08-23 10:30:00');
console.log(date.format('YYYY-MM-DD HH:mm:ss')); // 2024-08-23 10:30:00
// Format templates are dynamic: combine the supported tokens any way you like.
// Templates are compiled once and cached, so custom combinations stay fast.
console.log(date.format('YYYYMM')); // 202408
console.log(date.format('HHmm')); // 1030
console.log(date.format('[Created:] DD MMMM')); // Created: 23 August
// Safe error handling - catches invalid dates early!
try {
const invalid = new kk_date('invalid-date'); // β Throws error immediately
} catch (error) {
console.log('Invalid date prevented!'); // β
Error caught, no silent bugs
}
// Pre-validate dates without throwing errors (the static isValid() requires a format template)
if (kk_date.isValid('2024-13-45', 'YYYY-MM-DD')) { // false - invalid month
// Won't execute
}
if (kk_date.isValid('2024-08-23', 'YYYY-MM-DD')) { // true - valid date
const safeDate = new kk_date('2024-08-23'); // β
Safe to create
}
// isValid accepts ANY display-token template, not just the predefined ones
kk_date.isValid('31/12/2024 23:59', 'DD/MM/YYYY HH:mm'); // true
kk_date.isValid('03:45', 'mm:ss'); // true - minutes:seconds
// Optional strict mode (moment strict parity): real calendar days + wall-clock hours
kk_date.isValid('2021-02-30', 'YYYY-MM-DD'); // true - shape check only (default)
kk_date.isValid('2021-02-30', 'YYYY-MM-DD', true); // false - Feb 30 doesn't exist
kk_date.isValid('25:00:00', 'HH:mm:ss'); // true - day-overflow support (default)
kk_date.isValid('25:00:00', 'HH:mm:ss', true); // false - strict wall-clock hours
// Migrating from moment(value, format, true).isValid()? Pass true as the 3rd argument.
// Zero-config timezone conversion with automatic DST detection.
// Note: a naive string like '2024-08-23 10:30:00' is parsed in the process's LOCAL timezone.
// The examples below assume the process timezone is UTC (run with TZ=UTC, or call
// kk_date.setTimezone('UTC')). Pass an absolute instant ('...Z') for identical results everywhere.
const nyTime = new kk_date('2024-08-23 10:30:00').tz('America/New_York');
console.log(nyTime.format('HH:mm')); // 06:30 (EDT - automatically detected)
const tokyoTime = new kk_date('2024-08-23 10:30:00').tz('Asia/Tokyo');
console.log(tokyoTime.format('HH:mm')); // 19:30 (JST)
// Lightning-fast date manipulation
const tomorrow = new kk_date('2024-08-23 10:30:00').add(1, 'days');
console.log(tomorrow.format('YYYY-MM-DD')); // 2024-08-24Comprehensive documentation of all available methods and properties.
π Timezone Guide
Detailed guide on timezone handling, DST support, and conversion examples.
π Formatting Guide
Complete list of supported date/time formats with examples.
βοΈ Configuration Guide
How to configure global settings, locales, and timezone preferences.
Comprehensive benchmarks, optimization strategies, and performance monitoring.
π§ Advanced Usage
Advanced features, performance tips, and best practices.
π§ͺ Testing Guide
How to run tests and contribute to the project.
Timezone handling is one of the most critical aspects of date libraries. Inconsistent timezone conversions can lead to:
- Data corruption in financial applications
- Scheduling conflicts in calendar systems
- User confusion in global applications
- Production bugs that are hard to detect
| Library | Timezone Accuracy | DST Handling | Cross-Platform Consistency | Configuration Required |
|---|---|---|---|---|
| kk-date | β Perfect | β Automatic | β Consistent | β Zero Config |
| Moment.js | β Inconsistent | |||
| Day.js | β Inconsistent |
// Test instant: an absolute UTC instant (ISO-8601 with 'Z') is unambiguous on every machine.
// (A naive string like '2024-08-23 10:00:00' would instead be parsed in the process's local
// timezone, so pass an absolute instant when you need identical results everywhere.)
const testDate = '2024-08-23T10:00:00.000Z';
// kk-date: absolute instant converts to the same wall-clock on every system
const kkDate = new kk_date(testDate).tz('America/New_York');
console.log(kkDate.format('YYYY-MM-DD HH:mm:ss'));
// Result: 2024-08-23 06:00:00 (identical on every system)
// Moment.js: requires the moment-timezone add-on for .tz()
const moment = require('moment-timezone');
const momentDate = moment(testDate);
console.log(momentDate.tz('America/New_York').format('YYYY-MM-DD HH:mm:ss'));
// Result: 2024-08-23 06:00:00 (needs moment-timezone)
// Day.js: requires the utc + timezone plugins for .tz()
const dayjs = require('dayjs');
const dayjsDate = dayjs(testDate);
console.log(dayjsDate.tz('America/New_York').format('YYYY-MM-DD HH:mm:ss'));
// Result: 2024-08-23 06:00:00 (needs dayjs timezone plugin)kk-date provides identical results across different systems:
// Same code, same results on Windows, macOS, Linux, and Docker.
// Use an absolute instant (ISO-8601 with 'Z') so the value does not depend on the system timezone.
const baseTime = '2024-08-23T10:00:00.000Z';
// These results are identical on all platforms:
console.log(new kk_date(baseTime).tz('UTC').format('YYYY-MM-DD HH:mm:ss')); // 2024-08-23 10:00:00
console.log(new kk_date(baseTime).tz('America/New_York').format('YYYY-MM-DD HH:mm:ss')); // 2024-08-23 06:00:00
console.log(new kk_date(baseTime).tz('Europe/London').format('YYYY-MM-DD HH:mm:ss')); // 2024-08-23 11:00:00
console.log(new kk_date(baseTime).tz('Asia/Tokyo').format('YYYY-MM-DD HH:mm:ss')); // 2024-08-23 19:00:00kk-date automatically handles Daylight Saving Time transitions:
// DST transition dates - kk-date handles automatically.
// (Naive inputs below assume the process timezone is UTC; see the note above.)
const dstStart = new kk_date('2024-03-10 02:30:00'); // near DST start
const dstEnd = new kk_date('2024-11-03 02:30:00'); // near DST end
console.log(new kk_date('2024-03-10 02:30:00').tz('America/New_York').format('YYYY-MM-DD HH:mm:ss'));
// Result: 2024-03-09 21:30:00 (EST, correctly adjusted)
console.log(new kk_date('2024-11-03 02:30:00').tz('America/New_York').format('YYYY-MM-DD HH:mm:ss'));
// Result: 2024-11-02 22:30:00 (EDT, correctly adjusted)
// Calendar arithmetic keeps the wall-clock time across DST changes (like moment and Luxon), also
// where the change happens at midnight (America/Santiago, Asia/Beirut, America/Havana, ...):
kk_date.setTimezone('America/Santiago');
new kk_date('2024-04-06 00:00:00').add(1, 'days').format('YYYY-MM-DD HH:mm'); // '2024-04-07 00:00' (a 25-hour day)
kk_date.setTimezone('America/New_York');
new kk_date('2024-11-03 00:00:00').add(1, 'days').format('YYYY-MM-DD HH:mm'); // '2024-11-04 00:00'
new kk_date('2024-11-03 00:00:00').add(24, 'hours').format('YYYY-MM-DD HH:mm'); // '2024-11-03 23:00'
new kk_date('2024-03-10 02:30:00').format('HH:mm'); // '03:30' (02:30 does not exist that day)// β Moment.js & Day.js - Silent failures can cause production bugs
const momentDate = moment('invalid-date');
console.log(momentDate.isValid()); // false
console.log(momentDate.format('YYYY-MM-DD')); // 'Invalid date' - but continues!
// Risk: This string can propagate through your app causing unexpected behavior
// β
kk-date - Fail-fast approach prevents bugs
try {
const kkDate = new kk_date('invalid-date'); // Throws immediately!
} catch (error) {
// Handle error properly - no silent failures
console.log('Date validation failed - handling error safely');
}Moment.js and Day.js have fundamental issues:
- System Timezone Dependency: Results vary based on the server's timezone
- Manual DST Configuration: Requires complex setup for DST handling
- Plugin Requirements: Need additional plugins for timezone support
- Inconsistent Results: Same code produces different results on different systems
kk-date solves these problems with:
- Built-in timezone support (no plugins needed)
- Automatic DST detection (no manual configuration)
- Cross-platform consistency (same results everywhere)
- Zero configuration (works out of the box)
// Enable caching for repeated work
kk_date.caching({ status: true, defaultTtl: 3600 });
// Caching speeds up REPEATED operations (the same input parsed/formatted/converted again);
// see "Cache Performance Impact" below for the measured effect.
// (Distinct-input / first-time operations are already fast without caching.)
// Cached parses stay correct: a parse that depends on today's date ('15 March', '14:30') or on the
// global locale's month names is only reused on the same date / under the same language.
// Monitor cache performance
const stats = kk_date.caching_status();
const lookups = stats.totalHits + stats.totalMisses;
const hitRate = lookups > 0 ? ((stats.totalHits / lookups) * 100).toFixed(1) : 0;
console.log('Cache hit rate:', hitRate + '%'); // close to 100% for repeated inputs
console.log('Cache size:', stats.cacheSize + '/' + stats.maxCacheSize); // Current/Max
// Handle millions of operations efficiently
for (let i = 0; i < 1000000; i++) {
const date = new kk_date('2024-08-23 10:00:00');
date.tz('America/New_York'); // Much faster on repeat (served from cache)
}When to Enable Caching:
- π Data processing pipelines with repeated date operations
- π Global applications with multiple timezone conversions
- β‘ Real-time systems requiring low-latency date operations
- π Analytics dashboards with thousands of date calculations
- π APIs serving high-frequency date/time requests
// Automatic DST detection - no manual configuration needed
const summerTime = new kk_date('2024-08-23 10:00:00').tz('America/New_York'); // Automatically EDT
const winterTime = new kk_date('2024-12-23 10:00:00').tz('America/New_York'); // Automatically EST
console.log(summerTime.format('HH:mm')); // Summer time (EDT)
console.log(winterTime.format('HH:mm')); // Winter time (EST)// Every internal cache is bounded (format results, compiled templates, timezone offsets,
// Intl formatters, the optional parse cache), so long-running processes do not grow
const dates = [];
for (let i = 0; i < 10000; i++) {
dates.push(new kk_date('2024-08-23 10:00:00'));
}
// Lazy loading - Intl formatters for a timezone are created on its first use
const date = new kk_date('2024-08-23 10:00:00');
date.tz('America/New_York'); // creates (and caches) the New York formattersconst date = new kk_date('2024-08-23 10:30:00');
// Add/subtract time
date.add(2, 'hours'); // Add 2 hours
date.add(-1, 'days'); // Subtract 1 day
date.add(3, 'months'); // Add 3 months
// Start/end of periods
date.startOf('months'); // Start of month
date.endOf('weeks'); // End of weekconst date1 = new kk_date('2024-08-23');
const date2 = new kk_date('2024-08-25');
date1.isBefore(date2); // true
date1.isAfter(date2); // false
date1.isSame(date2); // false
// diff is measured as (other - this), so a later argument yields a positive result:
date1.diff(date2, 'days'); // 2
date2.diff(date1, 'days'); // -2// Global configuration
kk_date.setTimezone('UTC');
kk_date.config({ locale: 'en', weekStartDay: 1 }); // Monday
// Instance-specific configuration
const date = new kk_date('2024-08-23');
date.config({
timezone: 'America/New_York',
locale: 'tr',
weekStartDay: 0
});kk-date is compatible with React Native using the Hermes JavaScript engine.
Tested Environment:
- Expo 54
- React Native 0.81
- Hermes engine enabled
All core features work without any additional configuration:
- Date creation, formatting, and parsing
add(negative amounts subtract),set,get,diff,diff_range,startOf,endOfisBefore,isAfter,isSame,isBetween- Timezone conversions (
.tz()) fromNowrelative time- Caching system
Hermes has a known limitation with Intl.DateTimeFormat β the timeZoneName: 'longOffset' option either splits the GMT offset across multiple parts or is not supported at all. kk-date automatically detects and handles this with a built-in fallback:
// This works seamlessly on Hermes β no configuration needed
const date = new kk_date('2024-08-23 10:30:00');
const istanbul = date.tz('Europe/Istanbul');
console.log(istanbul.format('YYYY-MM-DD HH:mm')); // 2024-08-23 13:30The fallback uses a date-comparison method to calculate timezone offsets when longOffset is unavailable, ensuring correct DST-aware results across all timezones.
npm install kk-dateNo polyfills or additional packages required.
// CommonJS (Metro bundler compatible)
const kk_date = require('kk-date');
const date = new kk_date('2024-08-23');
console.log(date.format('DD/MM/YYYY')); // 23/08/2024- Chrome / Edge 80+
- Firefox 78+
- Safari 14+
- Node.js 22+
- Internet Explorer is not supported (the package ships untranspiled ES2020)
fromNow() needs Intl.RelativeTimeFormat; everything else needs Intl.DateTimeFormat with
timezone support. See the API Reference for details.
Note: All performance figures in this README come from our own benchmark suite on Node.js 26 and are refreshed by CI (the "Update Benchmark Docs" workflow runs
benchmark.js+benchmark2.jsafter the tests pass on every push todevthat changes JavaScript, uploads the JSON results and updates these tables). They are not guarantees β results vary by workload, hardware, Node version, and caching. Reproduce locally withnode benchmark.js/node benchmark2.js.
Our benchmark simulates real-world usage by processing 1000 sequential days with 100 operations per day. This reflects typical production scenarios where dates are processed in sequence rather than synthetic benchmarks.
Run the benchmark yourself:
node benchmark2.jsRepresentative run (Node.js 26) β refreshed by CI (see the "Update Benchmark Docs" workflow artifacts). Numbers vary run-to-run. Totals are for 100,000 operations per scenario:
| Operation | kk-date | Moment.js | Day.js | Luxon | vs Fastest Competitor |
|---|---|---|---|---|---|
| Date Creation & Formatting | 148ms | 1163ms | 768ms | 1026ms | ~81% less time (5.2x faster) than Day.js |
| Time Operations | 188ms | 1304ms | 635ms | 2910ms | ~70% less time (3.4x faster) than Day.js |
| Timezone Conversions | 462ms | 3385ms | 19514ms | 4586ms | ~86% less time (7.3x faster) than Moment |
| Complex Operations | 254ms | 2555ms | 1271ms | 3056ms | ~80% less time (5.0x faster) than Day.js |
kk-date wins the overall sequential run and every individual scenario above.
| Library | Total Time | Operations/sec | Performance |
|---|---|---|---|
| kk-date | 1.05s | 379,999 ops/sec | π Winner |
| Moment.js | 8.41s | 47,582 ops/sec | ~699% more time (8.0x slower) |
| Luxon | 11.58s | 34,546 ops/sec | ~1000% more time (11.0x slower) |
| Day.js | 22.19s | 18,027 ops/sec | ~2008% more time (21.1x slower) |
Net heap delta after creating 100,000 date instances (from node benchmark.js). This metric is dominated by GC timing, so it is noisy and several libraries can show a negative net delta β it is not a unique kk-date property. Sizes are measured the same way for every library by the docs generator: the gzipped total of the files Node.js loads for it (require() of kk-date; moment-timezone with its bundled zone data; Day.js with the utc, timezone and customParseFormat plugins the benchmark uses; Luxon). kk-date ships unminified source.
| Library | Heap Ξ / 100k instances* | Size (gzipped, as loaded) | DST Support |
|---|---|---|---|
| kk-date | ~-17 MB* | 67 KB | Built-in |
| Moment.js | ~-1 MB* | 78 KB | Plugin required |
| Day.js | ~-4 MB* | 7 KB | Plugin required |
| Luxon | ~+5 MB | 58 KB | Built-in |
* GC-timing artifact β varies run-to-run and can be negative for multiple libraries; reproduce with node benchmark.js.
kk-date's real memory advantages come from bounded caches (LRU eviction or clearing when full) and creating few intermediate objects β which keep long-running processes stable. The exact heap-delta number is not a guarantee.
// Measurement methodology:
const before = process.memoryUsage().heapUsed;
// Create 100,000 date instances...
const after = process.memoryUsage().heapUsed;
console.log((after - before) / 1024 / 1024, 'MB'); // GC-dependent; can be negativeWithout Cache vs With Cache (representative run):
- ~30% less time on repeated operations when cache is enabled
- Average operation time: ~37ms β ~26ms with cache
- Cache hit ratio: 100% for repeated operations
- Memory overhead: minimal (every cache is bounded: the parse cache evicts least-recently-used entries above 10,000, the internal caches are cleared when they reach their limit)
Why Enable Caching:
// Enable for high-performance scenarios
kk_date.caching({ status: true, defaultTtl: 3600 });
// Perfect for:
// β
Repeated timezone conversions (the biggest cache win)
// β
Frequently re-formatting the same inputs
// β
Large-scale data processing (handles 1M ops efficiently)
// β
Hot paths that re-convert/re-format the same instants- β‘ ~95% less time on average vs competing libraries (comprehensive benchmark)
- π up to ~98% less time in timezone operations (critical for global apps)
- π Big-data ready - efficient for bulk/1M-operation workloads
- πΎ Stable memory - bounded caches with automatic eviction; net heap delta is GC-dependent (often negative)
- βοΈ ~30% less time with smart caching enabled
- π Over 40x faster than Day.js in timezone conversions (Day.js takes β4122% more time)
- β Production tested with 1,454 tests
We welcome contributions! Please see our Contributing Guide for details.
npm test # Run all tests
npm test -- --watch # Run tests in watch mode
npm test -- --coverage # Run tests with coveragenode benchmark.js # Run comprehensive benchmark suite
node benchmark2.js # Run sequential 1000-day benchmarkThis project is licensed under the MIT License - see the LICENSE file for details.
- Inspired by modern date libraries like Moment.js and Day.js
- Built with performance and developer experience in mind
- Comprehensive timezone support using IANA timezone database
- π Issues: GitHub Issues
- π Documentation: Full Documentation
- π¬ Discussions: GitHub Discussions
This software is provided "as is", without warranty of any kind, express or implied, including but not limited to the warranties of merchantability, fitness for a particular purpose, and noninfringement. Use of the kk-date package is at your own risk. The maintainers and contributors do not guarantee that the package will function without errors or produce accurate results in all scenarios. In no event shall the authors or contributors be held liable for any damages, losses, or issues arising from the use of this package.
We're constantly working to improve kk-date! Here are some exciting features we're planning:
- π Web Workers Support - Asynchronous date operations for better performance
- π¦ Tree Shaking - Bundle size optimization for production builds
- π Plugin System - Extensible architecture for custom functionality
- π― Enhanced Caching - More intelligent cache strategies for specific use cases
β
Template Compilation shipped: format() now compiles any token combination once and caches it β
see the Formatting Guide.
- Enable caching for applications with repeated timezone operations
- Use instance configuration for date-specific settings
- Monitor cache statistics in production for optimal performance
- Test DST transitions thoroughly in your application
- Consider memory usage for high-frequency operations
Made with β€οΈ for the JavaScript community