DEV Community

Serhii Pimenov
Serhii Pimenov

Posted on

3 1

Datetime.js - Syntax sugar and not only...

Hi All! I would like to present to you my own view on the organization of syntactic sugar for working with date and time in javascript - Datetime.js.

Datetime.js is a minimalist JavaScript library that parses, validates, manipulates, and displays dates and times for modern browsers with comfortable modern API.

  • πŸ•’ Quick and accurate
  • πŸ’ͺ Immutable/mutable modes
  • πŸ”₯ Chainable
  • 🌐 I18n support
  • πŸ“¦ 4kb mini library
  • πŸ‘« All browsers supported

API

It's easy to use Datetime APIs to parse, validate, manipulate, and display dates and times.

Parse

datetime();
datetime("2020");
datetime("2020-12-31");
datetime("2020-12-31 23:59");
datetime(2020, 12, 31, 23, 59);
datetime([2020, 12, 31, 23, 59]);
Datetime.parse(...);
Datetime.fromString("16 November 1961 15:24", "dd mm %y h:i", "en")
Datetime.fromString("16 Ноября 1961 15:24", "dd mm %y h:i", "ru")
Enter fullscreen mode Exit fullscreen mode

Immutable/mutable

By default, datetime object is mutable. But, You can create immutable variable with method immutable:

var immutableDate = datetime('2020-12-21').immutable();
console.log(immutableDate); // 2020-12-21
console.log(immutableDate.add(1, 'month')); // 2021-01-21 this is a new object
console.log(immutableDate); // 2020-12-21
Enter fullscreen mode Exit fullscreen mode

Display

datetime().format('{YYYY} MM-DDTHH:mm:ss sss Z A');
datetime().strftime('{%Y} %n-%dT%H:%M:%S %Q %z %p');
Enter fullscreen mode Exit fullscreen mode

Get & set

You can set and get: millisecond, second, minute, hour, day, month, year, time (timestamp), ...

datetime().set('month', 3).month();
datetime().month(3).month();
Enter fullscreen mode Exit fullscreen mode

Manipulate

You can set: millisecond, second, minute, hour, day, month, year.

datetime().add(3, 'day').add(1, 'hour');
datetime().addDay(3).addHour(1);
Enter fullscreen mode Exit fullscreen mode

Align (Start From)

You can align date to: millisecond, second, minute, hour, day, month, year, quarter, week, isoWeek.

datetime().align("year"); // Will alignment to 1st Jan of year
datetime().align("month"); // Will alignment to 1st day of month
Enter fullscreen mode Exit fullscreen mode

Compare

datetime("2020").older("2021"); // return true
datetime("2020").younger("1972"); // return true
datetime("2020").between("2019", "2021"); // return true
datetime("2020-21-12").diff("1972-21-12"); // return {day: 17532, hour: 420768, millisecond: 1514764800000, minute: 25246080, month: 576, second: 1514764800, year: 48}
datetime("2020-21-12").distance("1972-21-12", "year"); // return 48
Enter fullscreen mode Exit fullscreen mode

Information

You can get different additional information about your date: count days in month, count days in year, number of quarter, year is leap, ...

datetime("2020-12-21").dayOfYear(); // return 356
datetime("2020-02-01").daysInMonth(); // return 29
datetime("2020-02-01").quarter(); // return 1
datetime("2020").isLeapYear(); // return true
Enter fullscreen mode Exit fullscreen mode

i18n

Datetime has great support for internationalization. By default, Datetime includes only english locale.
You can include many others:

In HTML

<script src="datetime.js"></script>
<script src="i18n/ru.js"></script>
Enter fullscreen mode Exit fullscreen mode

For NodeJS or use with Webpack or modern JS

import "@olton/datetime";
import "@olton/i18n/ru";
Enter fullscreen mode Exit fullscreen mode

With locales:

Datetime.fromString("16 Ноября 1961 15:24", "dd mm %y h:i", "ru");
datetime().useLocale('ru').format("DD MMM YYYY"); // 03 Π”Π΅ΠΊ 2020
Enter fullscreen mode Exit fullscreen mode

Plugins

You can create plugin and register it with functions Datetime.use() and Datetime.useStatic():

Create plugin

(function(global) {
    'use strict';

    Datetime.use({
        prototypeTest: function(val){
            return 0 === val || val ? val : "test";
        }
    });

    Datetime.useStatic({
        staticTest: function(val){
            return 0 === val || val ? val : "static test";
        }
    });
}());
Enter fullscreen mode Exit fullscreen mode

Include a plugin into page after datetime.js:

<script sec="datetime.js"></script>
<script sec="plugin.js"></script>
Enter fullscreen mode Exit fullscreen mode

And now use plugin:

<!-- Prototype methods -->
console.log(datetime().prototypeTest());
console.log(datetime().prototypeTest(123));

<!-- static methods  -->
console.log(Datetime.staticTest());
console.log(Datetime.staticTest(456));
Enter fullscreen mode Exit fullscreen mode

Datetime is licensed under an MIT license.

SurveyJS custom survey software

Simplify data collection in your JS app with a fully integrated form management platform. Includes support for custom question types, skip logic, integrated CCS editor, PDF export, real-time analytics & more. Integrates with any backend system, giving you full control over your data and no user limits.

Learn more

Top comments (2)

Collapse
 
yoursunny profile image
Junxiao Shi β€’
  • no TypeScript typings
  • no ES Modules, no tree-shaking support
Collapse
 
olton profile image
Serhii Pimenov β€’

at the moment I needed an ecmascript 5 implementation, so no modules. And I am not using Typescript, so no definitions.

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

AWS Security LIVE!

Hosted by security experts, AWS Security LIVE! showcases AWS Partners tackling real-world security challenges. Join live and get your security questions answered.

Tune in to the full event

DEV is partnering to bring live events to the community. Join us or dismiss this billboard if you're not interested. ❀️