UNPKG

vague-date

Version:

A tiny JavaScript library that formats precise time differences as a vague/fuzzy date, e.g. 'yesterday', 'today' or 'next week'.

1 lines 1.96 kB
!function(e){"use strict";function t(e){var t=n(e.units),u=Date.now(),o=r(e.from,t,u),i=r(e.to,t,u),a=o.timestamp-i.timestamp,f=Math.abs(a);return d(f,o,i)||b(f,a)}function n(e){if("undefined"==typeof e)return"ms";if("s"===e||"ms"===e)return e;throw new Error("Invalid units")}function r(e,t,n){if("undefined"==typeof e)return f(n);if("string"==typeof e&&(e=parseInt(e,10)),u(e)&&i(e))throw new Error("Invalid time");return"number"==typeof e&&"s"===t&&(e*=1e3),f(e)}function u(e){return o(e)===!1}function o(e){return"[object Date]"===Object.prototype.toString.call(e)&&isNaN(e.getTime())===!1}function i(e){return a(e)===!1}function a(e){return"number"==typeof e&&isNaN(e)===!1}function f(e){return o(e)?y(e):a(e)?s(e):void 0}function y(e){return c(e.getTime(),e)}function c(e,t){return{timestamp:e,day:t.getDay(),week:m(t),month:t.getMonth(),year:t.getYear()}}function m(e){var t=0,n=new Date(e.getFullYear(),0,1);return n.getDay()>e.getDay()&&(t=1),Math.floor((e.getTime()-n.getTime())/M.week)+t-1}function s(e){return c(e,new Date(e))}function d(e,t,n){return g(e,t,n)||h(e,t,n)||v(e,t,n)||D(t,n)}function g(e,t,n){return l(e,"day",t,n,"today","tomorrow","yesterday")}function l(e,t,n,r,u,o,i){if(e<2*M[t]){if(n[t]===r[t])return u;if(p(n[t],r[t],N[t]))return o;if(p(r[t],n[t],N[t]))return i}}function p(e,t,n){return e===t-1||e===n-1&&0===t}function h(e,t,n){return w(e,"week",t,n)}function w(e,t,n,r){return l(e,t,n,r,"this "+t,"next "+t,"last "+t)}function v(e,t,n){return w(e,"month",t,n)}function D(e,t){return e.year===t.year?"this year":e.year===t.year+1?"last year":e.year===t.year-1?"next year":void 0}function b(e,t){var n=Math.floor(e/M.year);return 0>t?"in "+n+" years":n+" years ago"}function k(){"function"==typeof define&&define.amd?define(function(){return T}):"undefined"!=typeof module&&null!==module?module.exports=T:e.vagueDate=T}var M={day:864e5,week:6048e5,month:26784e5,year:31536e6},N={day:7,week:52,month:12},T={get:t};k()}(this);