Skip to content

Instantly share code, notes, and snippets.

@tristanlins
Last active February 29, 2024 19:44
Show Gist options
  • Star 5 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tristanlins/6585391 to your computer and use it in GitHub Desktop.
Save tristanlins/6585391 to your computer and use it in GitHub Desktop.
Date.toW3CString() method to convert date objects into W3C date time format: yyyy-mm-ddThh:ii:ss+zz:zz
/**
* Convert a Date object to a string, according to W3C date time format: yyyy-mm-ddThh:ii:ss+zz:zz
*
* @memberOf Date
* @access public
* @license MIT
* @copyright 2013 Tristan Lins
* @author Tristan Lins <tristan.lins@bit3.de>
* @link https://gist.github.com/tristanlins/6585391
*/
Date.prototype.toW3CString = function () {
var year = this.getFullYear();
var month = this.getMonth();
month ++;
if (month < 10) {
month = '0' + month;
}
var day = this.getDate();
if (day < 10) {
day = '0' + day;
}
var hours = this.getHours();
if (hours < 10) {
hours = '0' + hours;
}
var minutes = this.getMinutes();
if (minutes < 10) {
minutes = '0' + minutes;
}
var seconds = this.getSeconds();
if (seconds < 10) {
seconds = '0' + seconds;
}
var offset = -this.getTimezoneOffset();
var offsetHours = Math.abs(Math.floor(offset / 60));
var offsetMinutes = Math.abs(offset) - offsetHours * 60;
if (offsetHours < 10) {
offsetHours = '0' + offsetHours;
}
if (offsetMinutes < 10) {
offsetMinutes = '0' + offsetMinutes;
}
var offsetSign = '+';
if (offset < 0) {
offsetSign = '-';
}
return year + '-' + month + '-' + day +
'T' + hours + ':' + minutes + ':' + seconds +
offsetSign + offsetHours + ':' + offsetMinutes;
}
/**
* Convert a Date object to a string, according to W3C date time format: yyyy-mm-ddThh:ii:ss+zz:zz
*
* @memberOf Date
* @access public
* @license MIT
* @copyright 2013 Tristan Lins
* @author Tristan Lins <tristan.lins@bit3.de>
* @link https://gist.github.com/tristanlins/6585391
*/
Date.prototype.toW3CString=function(){var f=this.getFullYear();var e=this.getMonth();e++;if(e<10){e="0"+e}var g=this.getDate();if(g<10){g="0"+g}var h=this.getHours();if(h<10){h="0"+h}var c=this.getMinutes();if(c<10){c="0"+c}var j=this.getSeconds();if(j<10){j="0"+j}var d=-this.getTimezoneOffset();var b=Math.abs(Math.floor(d/60));var i=Math.abs(d)-b*60;if(b<10){b="0"+b}if(i<10){i="0"+i}var a="+";if(d<0){a="-"}return f+"-"+e+"-"+g+"T"+h+":"+c+":"+j+a+b+":"+i};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment