npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

es-date-fiddler

v0.4.4

Published

ES Date helper

Downloads

65

Readme

es-date-fiddler

An ES Date with nifty extensions using ES Proxy. It is programmed in a class free object oriented coding style.

See demo for examples.

The datefiddler library by default delivers an enhanced ES-Date constructor, and a factory to create the constructor (DateXFactory). In the following we name the constructor $D.

$D is a normal ECMAScript Date constructor, without the need to use new. By using Proxy functionality one can use and/or create a localized ES-Date making a number of additional setters and getters (e.g. for arithmetic, formatting, locale awareness) available, as well as use all regular Date getters/setters/methods. So, to create a $D extended Date, instead of new Date(...) one uses $D(...).

Locaclized means that one can set (associate) the locale (e.g. de-DE) and/or timeZone identifier (e.g. Europe/Berlin) for an $D instance. Subsequently all retrieved date/time values from the instance are the values within the associated Timezone. By default an instance is associated with the local locale and timeZone identifier within the environment (browser, node) of the user.

Syntax

$D([dateOrLocale: Date | string | Array[Number] | {locale, timeZone}], [localeInfo: {locale, timeZone}])
  • dateOrLocale: can be a regular Date (new Date(...)), a (valid) date string ("2022/07/18"), a Number array or an Object with locale information (one of or both, e.g. {locale: "en-CA", timeZone: "America/Toronto"}). When no date can be inferred from dateOrLocale or the parameter is not given, the current date/time ('now') will be the instances' Date (associated with the users locale/Timezone). If dateOrLocale is and Object the current date with the locale parameters from the Object entries (if valid) will be the instances' Date.
  • localeInfo: when the first parameter is a Date or a date string, the second parameter can be used to associate locale information with that Date (see Locale).

A few examples:

const myDate = $D();
myDate.date = { year: myDate.year + 3, date: 12, month: 1 };
// one doesn't need to fill all values, the following keeps the current year of the XDate
myDate.date = { date: 12, month: 5 };
const nowInGermany = $D({locale: `de-DE`, timeZone: `Europe/Berlin`});
const aCloneInFrance = myDate.clone.relocate({locale: `fr-FR`, timeZone: `Europe/Paris`});
aCloneInFrance.locale; //=> {locale: `fr-FR`, timeZone: `Europe/Paris`}
const myDateHere = acCloneInFrance.cloneLocal;
myDateHere.locale; //=> {locale: [user environment locale], timeZone: [user environment time zone]};

Usage examples

The DEMO contains a lot of usage examples.

Import & initialize

There are three flavors of this library. One for scripts with type module (or projects with "type": "module" in package.json). One for the browser and one to use with require in NodeJS.

For each flavor, the script is (bundled and) minified. The location of the minified scripts is https://kooiinc.github.io/es-date-fiddler/Bundle

Note: earlier version of this module exported DateX. That's still available, but may be deprecated in a later version.

NodeJS commonjs

The cjs-code exports the constructor as DateX and $D and the factory DateXFactory.

Download links:

  • https://cdn.jsdelivr.net/gh/KooiInc/es-date-fiddler@latest/Node/index.bundle.cjs
  • https://kooiinc.github.io/es-date-fiddler/Node/index.bundle.cjs
// no package.json or "type": "commonjs" in your package.json
const $D = require("[local location of the cjs bundle]/index.bundle.cjs").$D;

// "type": "module" in your package.json:
// after download of the bundle from one of the download links
// Note: in this case you may as well use the esm import.
// See next chapter (ESM import) 
import {$D} from "[local location of the cjs bundle]/index.bundle.cjs";
/* ... */

ESM import

Import links:

  • https://cdn.jsdelivr.net/gh/KooiInc/es-date-fiddler@latest/Bundle/index.esm.min.js
  • https://kooiinc.github.io/es-date-fiddler/Bundle/index.esm.min.js
import $D = from "https://kooiinc.github.io/es-date-fiddler/Bundle/index.esm.min.js";

// Note: the module also exports a factory named DateXFactory. Use it as
import {DateXFactory} from "https://kooiinc.github.io/es-date-fiddler/Bundle/index.esm.min.js";
const $D = dxFactory();
/* ... */

Browser script

The browser-code makes the constructor available as window.$D or window.DateX, and the factory as window.DateXFactory.

Import links:

  • https://cdn.jsdelivr.net/gh/KooiInc/es-date-fiddler@latest/Bundle/index.browser.min.js
  • https://kooiinc.github.io/es-date-fiddler/Bundle/index.browser.min.js
<script 
  src="https://kooiinc.github.io/es-date-fiddler/Bundle/index.browser.min.js">
</script>
<script>
  const $D = window.$D;
  /* ... */
</script>

Getters and setters of $D instances

A number of getter (-methods) return the instance. These may be chained. For example:

const nextweek = $D(`2024/01/01`)
  .nextMonth
  .add(`-3 hours, 20 minutes, 5 seconds`)
  .relocate({locale: `en-AU`, timeZone: 'Australia/Darwin'})
  .format(`WD MM d yyyy hh:mmi:ss dp`); //=> 'Thursday February 1 2024 06:50:05 am'

Simple getters/setters are:

  • year: [instance].year or [instance].year = [value]
  • month: [instance].month or [instance].month = [value]
  • hour: [instance].hour or [instance].hour = [value]
  • minutes: [instance].minutes or [instance].minutes = [value]
  • seconds: [instance].seconds or [instance].seconds = [value]
  • ms: [instance].ms or [instance].ms = [value]
  • date: [instance].date (see additional getter/setters for setter)
  • time: [instance].time returns an [h, m, s, ms] (see additional getters/setters for setter)
  • locale: returns the current value of locale and timeZone identifier ({locale, timeZone}). See additional getters/setters for the setter.

Additional getters are

  • clonechainable: clones the $D instance to a new $D instance, including its associate locale/timeZone.
  • cloneLocalchainable: clones the $D instance to new $D instance with the default (your) locale/timeZone.
  • cloneDateTo([dateTo]: Date|$D)chainable: copies the date part of the $D instance to dateTo. When dateTo is missing the date part is copied to now.Returns a new $D instance for [dateTo].
  • cloneTimeTo([dateTo]: Date/$D)chainable: clones the time part of the $D instance to dateTo. When dateTo is missing the time part is copied to now.Returns a new $D instance for [dateTo].
  • daysInMonth: returns the days in the month of the $D instance Date.
  • daysUntil(nextDate: Date | $D instance): returns the number of days between two dates. The time of both dates will not be considered, so returns the number of days between midnight from - and to date.
  • dateStr: get the date part from the instance date as string. The string will be formatted using the instances' associated locale information.
  • dateISOStr: get the date part from the instance date as ISO 8601 string (yyyy-mm-dd).
  • firstWeekday([{sunday: boolean, midnight: boolean}])chainable: retrieve new instance from the date of the instances' first weekday, starting from monday (default) or sunday ({ sunday: true }) with the instances' time (default) or the time set to midnight ({ midnight: true }).
  • getTimezone: retrieves the time zone of the instance date (either the associated - or the local time zone).
  • hasDST: determine if the instance date timeZone is within a Daylight Saving Time zone, using the instances' associated timeZone information.
  • isLeapYear: calculates and returns if the $D instance is a leap year (return true or false).
  • ISO: short for .toISOString(), so returns the ISO string representation of the $D instance
  • local: [instance].local: tolocalestring() equivalent, but [instance].local will use the instances' locale/timeZone (either set or the default (your) locale/timeZone).
  • monthName: [instance.monthName]: The name of the month (january, february ...), using the instances' associated locale.
  • next(day: string, [{midnight: boolean (default false)}])chainable: retrieve an instance clone for the next [day] (one of mon, tue, ... sun), with the current time, or midnight ({midnight: true}).
  • self: returns the original Date as a plain ES Date.
  • timeStr(includeMS: boolean): retrieve time as string (hh:mm:ss[.ms]). The result will be the time within the instances' associated timeZone, with a 24-hour notation (hh:mm:ss[.ms]).
  • timeZone: retrieves the timeZone currently associated with the instance.
  • timeDiffToHere: retrieves the time difference (hour, minutes) from an instance to the date within the default (your) timeZone.
  • values(asArray: boolean): returns the values (year, month etc.) using the associated locale/timeZone as Object:
    {year, month, date, hour, minutes, seconds, milliseconds, dayPeriod, monthName, weekDay, resolvedLocale, valuesArray}.
  • weekDay: [instance.weekDay] The name of the weekday (monday, tuesday ...), using the instances' associated locale.

Additional getter and/or setters are:

  • date (setter): [instance].date = /* Object literal. One or more of { year, month, date }; */
  • time (setter): [instance].time = /* Object literal. One or more of { hour, minutes, seconds, milliseconds }; */
  • locale (setter): [instance].locale = /* Object literal. One or both of { locale: [locale], timeZone: [timeZone] } */. Notes:
    • it is important to use valid values. When either locale or timeZone are not valid (e.g. {timeZone: "London"}), some stringify-getters (format, local) will revert to ones current locale/timeZone. See this wikipedia page for all possible values.
  • relocate(newLocale: Object: {locale: string, timeZone: string})chainable: locale setter as method. Associate [locale] and/or [timeZone] with the current $D instance.
  • removeLocalechainable: remove associated locale information from the $D instance (note: resets to local (your) locale).
  • format(template: string, options: string): format the date (locale specific) using a template string. This uses a specific library. See Github for all about the syntax.
  • differenceFrom(date: instance or ES-Date): retrieve the instances' absolute difference from [date]. Returns:
    {from, to, years, months, days, hours, minutes, seconds, milliseconds, full (string from all values), clean (string from non zero values)}
    See the demo for a few examples.
  • relocate({locale, timeZone}: Object)chainable: (re)set the locale of the instance. When one or neither of locale/ timeZone is/are present, the locale will be set to {locale: 'utc', timeZone: 'Etc/UTC'}.

Setters to add or subtract days, years, hours etc.

The following setters use the following basic syntax for adding or subtracting things from the date at hand.

  your$D.[add/subtract](
    "[n year(s)], [n month(s)], [n week(s)], [n day(s)], 
     [n hour(s)], [n minute(s)], [n second(s)], [n millisecond(s)]"
  );

See the demo for examples.

Notes:

  • all setters below change the instance Date. If one doesn't want that, clone the $D instance first, e.g const nextYear = [instance].clone.nextYear.
  • all setters below are chainable, e.g. [instance].nextYear.add("15 days").subtract("2 hours, 30 minutes").
  • for convenience the $D constructor has the property (getter) now to create an instance with the current Date. $D.now is equivalent to $D().

  • add(...things2Add: string | string[])chainable: add [things2Add] to the $D instance and set its value to the result. [thing2Add] can be either a comma delimited string, or a number of strings, e.g. [instance].add("1 day, 5 hours") or [instance].add("1 day", "5 hours")
  • subtract(...things2Subtract: string | string[])chainable: subtract [things2Add] from the $D instance and set its value to the result. [thing2Add] can be either a comma delimited string, or a number of strings, e.g. [instance].subtract("1 day, 5 hours") or [instance].subtract("1 day", "5 hours").
    • Note: subtract is for convenience, it can also be written as [instance].add("-1 day, -5 hours")
  • addYears(n: Number)chainable: add n years to the $D instance and set its value to the result. n May be negative.
  • addMonths(n: Number)chainable: add n months to the $D instance and set its value to the result. n May be negative.
  • addWeeks(n: Number)chainable: add n weeks to the $D instance and set its value to the result. n May be negative.
  • addDays(n: Number)chainable: add n days to the $D instance and set its value to the result. n May be negative.
  • nextYearchainable: add one year to the $D instance and set its value to the result.
  • previousYearchainable: subtract one year to the $D instance and set its value to the result.
  • nextWeekchainable: add one week (7 days) to the $D instance and set its value to the result.
  • previousWeekchainable: subtract one week (7 days) from the $D instance and set its value to the result.
  • nextMonthchainable: add one month to the $D instance and set its value to the result.
  • previousMonthchainable: subtract one month to the $D instance and set its value to the result.
  • tomorrowchainable: add one day to the $D instance and set its value to the result.
  • yesterdaychainable: subtract one day from the $D instance and set its value to the result.

Instance utilities

now, validateLocale

  • now: (getter) as may be expected, delivers an instance from the current date. It is equivalent to $D(().
  • validatedLocale(locale: Object {locale, timeZone}): validate a locale string, a timeZone label or both
  • dateFromString(dateString: string, format: string (default "ymd")): create an ES-Date from a [dateString], using [format] to indicate the position of year (y), month (m) and date (d) in the given date string.

extendWith: create additonal setters and getters for $D

One can create additional setters/getter (properties/methods) to the constructor using:

$D.extendWith({name: string, fn: Function, isMethod: boolean, proxifyResult: boolean})

  • fn: Function: the function to use. The function signature is [fn](date, [one or more arguments]). The [date] parameter is the instance date, which within the function [fn] will be available as a $D instance
  • isMethod: boolean by default the extension function is added as property (getter) when isMethod is false. When isMethod is true, the function is considered (and callable) as a method and can receive parameters ([instance][name](dateValue, ...args)).
  • proxifyResult: boolean: When true and fn returns the instance date, enables chaining by returning a $D instance. Default value is false. May be useful when one is not sure the return value will be the actual instance instead of a 'plain' Date.

The demo contains examples.