Permalink
Browse files

Initial commit

  • Loading branch information...
0 parents commit 0103943015d7f75c31bd6605a4659733d80700ce @tj tj committed Sep 25, 2012
Showing with 123 additions and 0 deletions.
  1. +2 −0 .gitignore
  2. +11 −0 Makefile
  3. +45 −0 Readme.md
  4. +12 −0 component.json
  5. +53 −0 index.js
@@ -0,0 +1,2 @@
+components
+build
@@ -0,0 +1,11 @@
+
+build: components index.js
+ @component build --dev
+
+components:
+ @component install --dev
+
+clean:
+ rm -fr build components template.js
+
+.PHONY: clean
@@ -0,0 +1,45 @@
+
+# relative-date
+
+ Relative dates in words
+
+## Installation
+
+ $ component install component/relative-date
+
+## API
+
+### relative(date)
+
+ Return the `date` in words relative to `Date.now()`:
+
+```js
+var relative = require('relative-date');
+var date = new Date(Date.now() + 2000);
+
+var str = relative(date) + ' ago';
+// => "2 seconds ago"
+```
+
+ An empty string `""` is returned when the difference
+ is below one second. You may use this to default
+ the string as shown here:
+
+```js
+var str = relative(new Date) || 'just now';
+// => "just now"
+
+var str = relative(new Date);
+if (str) str = 'assignment due in ' + str;
+else str = 'assignment due';
+
+// => "assignment due"
+```
+
+### relative(date, other)
+
+ Same as above, relative to `other` instead of `Date.now()`.
+
+# License
+
+ MIT
@@ -0,0 +1,12 @@
+{
+ "name": "relative-date",
+ "repo": "component/relative-date",
+ "description": "Relative dates in words",
+ "version": "0.0.1",
+ "keywords": ["date", "relative", "utility"],
+ "dependencies": {},
+ "development": {},
+ "scripts": [
+ "index.js"
+ ]
+}
@@ -0,0 +1,53 @@
+
+/**
+ * Expose `relative`.
+ */
+
+module.exports = relative;
+
+/**
+ * Constants.
+ */
+
+var second = 1000;
+var minute = 60 * second;
+var hour = 60 * minute;
+var day = 24 * hour;
+var week = 7 * day;
+var year = day * 365;
+var month = year / 12;
+
+/**
+ * Return `date` in words relative to `other`
+ * which defaults to now.
+ *
+ * @param {Date} date
+ * @param {Date} other
+ * @return {String}
+ * @api public
+ */
+
+function relative(date, other) {
+ other = other || new Date;
+ var ms = date - other;
+
+ if (ms < second) return '';
+
+ if (ms == second) return 'one second';
+ if (ms < minute) return Math.ceil(ms / second) + ' seconds';
+
+ if (ms == minute) return 'one minute';
+ if (ms < hour) return (ms / minute).toFixed(1) + ' minutes';
+
+ if (ms == day) return 'one day';
+ if (ms < week) return Math.ceil(ms / day) + ' days';
+
+ if (ms == week) return 'one week';
+ if (ms < month) return (ms / week).toFixed(1) + ' weeks';
+
+ if (ms == month) return 'one month';
+ if (ms < year) return (ms / month).toFixed(1) + ' months';
+
+ if (ms == year) return 'one year';
+ return (ms / year).toFixed(1) + ' years';
+}

0 comments on commit 0103943

Please sign in to comment.