diff date.js @ 0:f62b5c395a48

Initial commit.
author Emmanuel Gil Peyrot <linkmauve@linkmauve.fr>
date Sat, 04 Jun 2011 05:02:47 +0200
parents
children 82905edac9d8
line wrap: on
line diff
new file mode 100644
--- /dev/null
+++ b/date.js
@@ -0,0 +1,75 @@
+Date.prototype.set8601 = function (string) {
+	var regexp = "([0-9]{4})(-([0-9]{2})(-([0-9]{2})" +
+		"(T([0-9]{2}):([0-9]{2})(:([0-9]{2})(\.([0-9]+))?)?" +
+		"(Z|(([-+])([0-9]{2}):([0-9]{2})))?)?)?)?";
+	var d = string.match(new RegExp(regexp));
+
+	var offset = 0;
+	var date = new Date(d[1], 0, 1);
+
+	if (d[3]) { date.setMonth(d[3] - 1); }
+	if (d[5]) { date.setDate(d[5]); }
+	if (d[7]) { date.setHours(d[7]); }
+	if (d[8]) { date.setMinutes(d[8]); }
+	if (d[10]) { date.setSeconds(d[10]); }
+	if (d[12]) { date.setMilliseconds(Number("0." + d[12]) * 1000); }
+	if (d[14]) {
+		offset = (Number(d[16]) * 60) + Number(d[17]);
+		offset *= ((d[15] == '-') ? 1 : -1);
+	}
+
+	offset -= date.getTimezoneOffset();
+	var time = (Number(date) + (offset * 60 * 1000));
+	this.setTime(Number(time));
+
+	return this;
+}
+
+Date.prototype.to8601 = function(){
+	function pad(n){return n<10 ? '0'+n : n}
+	return this.getUTCFullYear()+'-'
+		+ pad(this.getUTCMonth()+1)+'-'
+		+ pad(this.getUTCDate())+'T'
+		+ pad(this.getUTCHours())+':'
+		+ pad(this.getUTCMinutes())+':'
+		+ pad(this.getUTCSeconds())+'Z';
+}
+
+Date.prototype.getRelative = function(){
+	const s = 1000, m = s*60, h = m*60, d = h*24, y = d*365, M = y/12,
+	      ref = Date.now(),
+	      input = this.getTime(),
+	      delta = ref - input,
+	      year = Math.round((delta/y)*10)/10,
+	      month = Math.round((delta/M)*10)/10,
+	      day = Math.round((delta/d)*10)/10,
+	      hour = Math.round((delta/h)*10)/10,
+	      minute = Math.round((delta/m)*10)/10;
+
+	if (year == 1)
+		return "a year ago";
+	if (year > 1)
+		return Math.round(year)+" years ago";
+
+	if (month == 1)
+		return "a month ago";
+	if (month > 1)
+		return Math.round(month)+" months ago";
+
+	if (day == 1)
+		return "today";
+	if (day > 1)
+		return Math.round(day)+" days ago";
+
+	if (hour == 1)
+		return "an hour ago";
+	if (hour > 1)
+		return Math.round(hour)+" hours ago";
+
+	if (minute == 1)
+		return "a minute ago";
+	if (minute > 1)
+		return Math.round(minute)+" minutes ago";
+
+	return "just now";
+};