t4mat
Tiny (1 KB when miniified and gzipped) & easy to use library for date formatting
Installation
Download
Download the t4mat.min.js
file from the dist
directory.
NPM
npm install --save t4mat
Usage
Note: This library can be either used in node or in the browser. The following examples are using the node environment.
const t4mat = ;var myDate = "2016-01-01T16:40:01.083Z"; // ISO stringvar formatted = ; // > "2016 - 1 - 1"
As the above example demonstrates, the library is a mere function that takes an object as an argument, this object would have the following properties:
time
(aliases:t1
,t
): The date in question, which can be a milliseconds since the epoch time (e.g.1451666401083
), an ISO String like the example above, or a date object. In fact it can be any value that thenew Date()
constructor in javascript can take.- format: This is just a string having short codes that are delimited by the curly braces. So for the above example, this format:
{d} / {m}
would return:1 / 1
, while this format:{yyyy} ({d})
would return:2016 (1)
. The following shortcodes are available in the format:{d}
The day of the month (Example:1
).{dd}
The day of the month with a0
prefix when it's less than 10 (Example:01
).{D}
The day of the week, short version (Example:Wed.
).{DD}
The day of the week, full version (Example:Wednesday
).{m}
The numerical representation of the month (Example:1
).{mm}
The numerical representation of the month, with a0
prefix when it's less than 10 (Example:01
).{M}
The literal representation of the month, short version (Example:Jan.
).{MM}
The literal representation of the month, full version (Example:January
).{Y}
Two digits representation of the year (Example:16
).{y}
same as above.{YY}
same as above.{yy}
same as above.{YYYY}
Full year (Example2016
).{yyyy}
same as above.{yyy}
same as above.{YYY}
same as above.{R}
Relative representation of the date/time, short version (Example4 yrs ago
).{RR}
Relative representation of the date/time, full version (Example4 years ago
).
About the relative time
By default the time you pass in the object will be represented relatively to the current time. However, if you want it to be calculated relative to another time, pass the base time as base
in the object.
- Example:
Let's suppose that the current time in the browser is 2016-01-02T00:00:00.000Z
Running this code:
var formatted = ;console;// > "1 day ago" var formatted2 = ;console;// > "in 1 day"
So by default the relative time calculation takes the current browser/machine time as the base. However if you wanted to pass your own base time then pass it as t2
:
var formatted = ;console;// > "1 day ago" var formatted2 = ;console;// > "2 day ago"