This library is deprecated/replaced with TickTock.js.
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.
$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"), aNumberarray or an Object with locale information (one of or both, e.g.{locale: "en-CA", timeZone: "America/Toronto"}). When no date can be inferred fromdateOrLocaleor the parameter is not given, the current date/time ('now') will be the instances' Date (associated with the users locale/Timezone). IfdateOrLocaleis andObjectthe current date with the locale parameters from the Object entries (if valid) will be the instances' Date.localeInfo: when the first parameter is aDateor 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]};The DEMO contains a lot of usage examples.
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.
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";
/* ... */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();
/* ... */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>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'year:[instance].yearor[instance].year = [value]month:[instance].monthor[instance].month = [value]hour:[instance].houror[instance].hour = [value]minutes:[instance].minutesor[instance].minutes = [value]seconds:[instance].secondsor[instance].seconds = [value]ms:[instance].msor[instance].ms = [value]date:[instance].date(see additional getter/setters for setter)time:[instance].timereturns 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.
clonechainable: clones the$Dinstance to a new$Dinstance, including its associate locale/timeZone.cloneLocalchainable: clones the$Dinstance to new$Dinstance with the default (your) locale/timeZone.cloneDateTo([dateTo]: Date|$D)chainable: copies the date part of the$Dinstance todateTo. WhendateTois missing the date part is copied to now.
Returns a new$Dinstance for[dateTo].cloneTimeTo([dateTo]: Date/$D)chainable: clones the time part of the$Dinstance todateTo. WhendateTois missing the time part is copied to now.
Returns a new$Dinstance for[dateTo].daysInMonth: returns the days in the month of the$Dinstance 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$Dinstance is a leap year (return true or false).ISO: short for.toISOString(), so returns the ISO string representation of the$Dinstancelocal:[instance].local:tolocalestring()equivalent, but[instance].localwill 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 originalDateas a plain ESDate.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 asObject:
{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.
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.
- it is important to use valid values. When either locale or timeZone are not valid (e.g.
relocate(newLocale: Object: {locale: string, timeZone: string})chainable: locale setter as method. Associate [locale] and/or [timeZone] with the current$Dinstance.removeLocalechainable: remove associated locale information from the$Dinstance (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 oflocale/timeZoneis/are present, the locale will be set to{locale: 'utc', timeZone: 'Etc/UTC'}.
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,
clonethe$Dinstance first, e.gconst nextYear = [instance].clone.nextYear. - all setters below are chainable, e.g.
[instance].nextYear.add("15 days").subtract("2 hours, 30 minutes"). - for convenience the
$Dconstructor has the property (getter)nowto create an instance with the currentDate.$D.nowis equivalent to$D().
add(...things2Add: string | string[])chainable: add [things2Add] to the$Dinstance 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$Dinstance 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:
subtractis for convenience, it can also be written as[instance].add("-1 day, -5 hours")
- Note:
addYears(n: Number)chainable: addnyears to the$Dinstance and set its value to the result.nMay be negative.addMonths(n: Number)chainable: addnmonths to the$Dinstance and set its value to the result.nMay be negative.addWeeks(n: Number)chainable: addnweeks to the$Dinstance and set its value to the result.nMay be negative.addDays(n: Number)chainable: addndays to the$Dinstance and set its value to the result.nMay be negative.nextYearchainable: add one year to the$Dinstance and set its value to the result.previousYearchainable: subtract one year to the$Dinstance and set its value to the result.nextWeekchainable: add one week (7 days) to the$Dinstance and set its value to the result.previousWeekchainable: subtract one week (7 days) from the$Dinstance and set its value to the result.nextMonthchainable: add one month to the$Dinstance and set its value to the result.previousMonthchainable: subtract one month to the$Dinstance and set its value to the result.tomorrowchainable: add one day to the$Dinstance and set its value to the result.yesterdaychainable: subtract one day from the$Dinstance and set its value to the result.
now: (getter) as may be expected, delivers an instance from the current date. It is equivalent to$D(().validatedLocale(locale: Object {locale, timeZone}): validate alocalestring, atimeZonelabel or bothdateFromString(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.
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$DinstanceisMethod: booleanby default the extension function is added as property (getter) whenisMethodisfalse. WhenisMethodistrue, the function is considered (and callable) as a method and can receive parameters ([instance][name](dateValue, ...args)).proxifyResult: boolean: Whentrueandfnreturns the instance date, enables chaining by returning a$Dinstance. Default value isfalse. 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.