📜 ⬆️ ⬇️

Library datef - date formatting

Allow me to submit datef - mini-JS-library for displaying dates in different formats.
Briefly I will describe the available features:

Examples of using:
datef('dd.MM.YY', new Date()); // "13.08.12" datef('dd.MM.YY'); //    —  «» var d = new Date(); d.setFullYear(2045); datef('dd.MM.YYYY', d); // "13.08.2045" //     : datef.formatters.ISODateTimeTZ(); // "2012-08-13T15:01:29 -04:00" //     … datef.register('myFormat', 'dMYY'); datef.formatters.myFormat(); // "13.8.12" //        var myFormat = datef.createFormatter('dMYY'); 


How does it work?
The most interesting thing for me, from the point of view of the code, was compliance with the ecology - that is, working with a system of modules like nodejs and requirejs / amd. Fortunately, everything turned out to be quite simple:
 (function () { 'use strict'; var datef = { answer: 42 }; // Expose our precious function to outer world. if (typeof exports !== 'undefined') { // node.js way module.exports.datef = datef; } else if (typeof define === 'function' && define.amd) { // requirejs/amd env define( 'datef', [], function () { return datef; } ); } else { // plain browser environment root.datef = datef; } })(); 

Replacing the name of my library with your own, you can easily and quickly turn your mini-utility into a module with support for different environments.
As for the library core itself, everything is straightforward, and, even, probably, boring: there is a set of tokens that serve as keys in the object. The values ​​of these keys are functions that transfer the actual desired date and which return the corresponding value. Based on the same tokens, a regular expression is generated, with which the format string is parsed.

But why?
As you know, in Javascript there is no support for something like Date # toFormat. There is only a non-standard Gekko'vsky Date # toLocaleFormat . At one point, I realized that I was dragging the same primitive bicycles of the kind utils.date.humanDate, utils.date.humanTime and the like from a project to a project — and began to look for proven, flexible bicycles solutions created by experienced developers.
Unfortunately, there were only some very old libraries - usually monstrous, complex decisions on working with dates, often, besides, sinning with the Date.prototype extension, and I decided to make my own, modern and expandable library.

Where is feature X?
The plans mean - the creation of locales, test coverage and license selection. If something is missing for you, then the code is not without reason posted on the github :)
')
Why is it incompatible with anything?
Because 80% of the functionality of strftime or PHP date () takes 20% of the time; the remaining 20% ​​of the functionality will be needed by 20% of people and will require 80% of the time. And I wanted to create a quick solution with readable tokens.

Source: https://habr.com/ru/post/149514/


All Articles