JavaScript

Dateadjust Method

Syntax

Date.adjust(unit,value)

Date.adjust(unit,'=',value)

Arguments

unitstring

The unit of measurement to adjust the date by. Values can be "year", "quarter", "month", "week", "weekday", "day" (or "date"), "hour", "minute", "second", "milliseconds" and "duration".

valuestringnumber

The time to set on the date.

Description

Extension to the native date variable to allow for the quick adjustment of a given date.

Discussion

The Date.adjust method takes a unit and value to adjust the date by.

If the second argument is a string with the character "=" in it, then the date will be adjusted absolutely with the given value in the third argument. If the second argument is a number, then the number will be added to the current corresponding value. If the value has a decimal, then the next logical unit will be adjusted as well. So adjusting a month by "4.5" will move the date by four months and then half the number of days in that month.

In all cases but "weekday", "milliseconds" and "duration", a value of "start" or "end" can be used to adjust the date to the start or end of the given unit. The values "start and "end" can be shortened to "s" and "e". For example, if the unit is "month" then "end" would month the date to the last day of the current month.

In the case of "weekday", either the zero based day of the week can be passed in, or any of the day names from A5.d.date.days or A5.d.date.daysShort arrays.

In the case of "duration", a duration string can be passed in in either clock format, or ISO 8601 duration format, for example: "1:15:22.003" for one hour, 15 minutes, 22 second and 3 milliseconds

Example

var d = new Date(2018,7,10);
d.adjust('week','start');
// d = Aug 5 2018
d.adjust('date','=',20);
// d = Aug 20 2018
d.adjust('quarter',-1);
// d = Apr 01 2018
d.adjust('weekday','wed');
// d = Apr 04 2018