Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with
or
.
Download ZIP

Loading…

Add toRelativeDuration() method #22

Closed
wants to merge 1 commit into from

2 participants

@robin900

I needed a way to express the difference between two dates as a mere duration, with "ago" or "from now".

@robin900 robin900 Add toRelativeDuration() method
I needed a way to express the difference between two dates as a mere duration, with "ago" or "from now".
8dfb04f
@davglass
Owner

This is not the proper place to file a pull request, please file it with the owner of the module:

http://yuilibrary.com/gallery/show/torelativetime

@davglass davglass closed this
@robin900

OK, sorry about that!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Commits on Oct 26, 2012
  1. @robin900

    Add toRelativeDuration() method

    robin900 authored
    I needed a way to express the difference between two dates as a mere duration, with "ago" or "from now".
This page is out of date. Refresh to see the latest.
Showing with 23 additions and 2 deletions.
  1. +23 −2 src/gallery-torelativetime/js/torelativetime.js
View
25 src/gallery-torelativetime/js/torelativetime.js
@@ -3,27 +3,47 @@
* instance to a string like "2 days ago". If the second parameter is
* provided, the time delta is in reference to this date.
*
+ * Also available is Y.toRelativeDuration(Date, refDate) which will
+ * omit the "ago" or "from now" phrase from the returned string, and provide
+ * just a duration in human-readable form.
+ *
* @module gallery-torelativetime
*
* @class YUI~toRelativeTime
*/
/**
+ * @method toRelativeDuration
+ * @param d {Date} the Date to translate.
+ * @param from {Date} (optional) reference Date. Default is now.
+ * @return {String} the duration between from and d, in human readable form
+ */
+function toRelativeDuration(d,from) {
+ return toRelativeTime(d, from, true);
+}
+
+/**
* @method toRelativeTime
* @param d {Date} the Date to translate.
* @param from {Date} (optional) reference Date. Default is now.
+ * @param durationOnly {boolean} (optional) if true, omit "ago" or "from now" in the returned string.
* @return {String} the delta between from and d, in human readable form
*/
-function toRelativeTime(d,from) {
+function toRelativeTime(d,from,durationOnly) {
d = d || new Date();
+ var useFromNow = (from == undefined);
from = from || new Date();
+ durationOnly = (!!durationOnly);
var delta = (from.getTime() - d.getTime()) / 1000,
strings = toRelativeTime.strings,
time = "",
rel, tmp, months, years;
- if (arguments.length < 2) {
+ if (durationOnly) {
+ rel = "";
+ }
+ else if (useFromNow) {
rel = (delta < 0) ? strings.fromnow : strings.ago;
} else {
rel = (delta < 0) ? strings.ahead : strings.before;
@@ -126,3 +146,4 @@ toRelativeTime.strings = {
};
Y.toRelativeTime = toRelativeTime;
+Y.toRelativeDuration = toRelativeDuration;
Something went wrong with that request. Please try again.