DatetoRelative Method





How many units of time to show in the relative date. The default is 1, a value of -1 can be used to show all units.


The scope of difference. By default it will be the full range from years to seconds. See Date.diff.


Extension to the native date variable to allow the conversion of the date into string showing the date relative to the current date.


The Date.toRelative method can be used to show a date in a relative format such as "3 days ago". The "precision" argument can be used to change the level of detail of the relative date. A value of 1 would return "3 days ago" or "in 1 hour", while a value of 2 might show "3 days 2 hours ago" or "in 1 hour 5 minutes".

The "scope" argument can be used to default the granularity of the units of time used. For instance, setting it to a value of "years-days" will only ever show the difference in days, week, months and years, but never in hours, minutes or seconds. If the given "scope" results in a relative date that is the same, then the corresponding "same" template for the smallest unit is used. This means that if the smallest unit of comparison is "weeks", and the date is within a week of the current date then the value returned would be whatever is in the same week template (e.g. "this week").


var d = new Date();
var dStr = d.toRelative();
// dStr = 'in 2 days'
dStr = d.toRelative(2);
// dStr = 'in 2 days 1 hour'