Date setTimezoneOffset method


As you all know, all date methods work only in the context of local time (user) or UTC, but sometimes you want to work in other contexts (time zones), the standard js forgot about the antagonist for getTimezoneOffset, and this is my method:

/**
 * Set the timezone offset from the local timezone offset.
 * Argument "minutes" => -UTC±XX:XX, default = local offset.
 * Property "timezoneOffset" => last-set offset.
 * Return => milliseconds.
 */
Date.prototype.setTimezoneOffset = function(minutes) { 
	var _minutes;
	if (this.timezoneOffset == _minutes) {
		_minutes = this.getTimezoneOffset();
	} else {
		_minutes = this.timezoneOffset;
	}
	if (arguments.length) {
		this.timezoneOffset = minutes;
	} else {
		this.timezoneOffset = minutes = this.getTimezoneOffset();
	}
	return this.setTime(this.getTime() + (_minutes - minutes) * 6e4);
};

// Example

var date = new Date(), text = '\nExample\n\n';
// milliseconds
text += 'time1\t' + date.getTime() + '\n';
// UTC time
text += '  UTC\t' + date.toUTCString() + '\n';
// local time
text += 'local\t' + date + '\t' + date.timezoneOffset + '\n';
// -UTC-04:00 => 240
date.setTimezoneOffset(240);
text += 'set-4\t' + date + '\t' + date.timezoneOffset + '\n';
// -UTC+06:00 => -360
date.setTimezoneOffset(-360);
text += 'set+6\t' + date + '\t' + date.timezoneOffset + '\n';
// -UTC±00:00 => 0
date.setTimezoneOffset(0);    
text += 'set 0\t' + date + '\t' + date.timezoneOffset + '\n';
// no argument => reset
date.setTimezoneOffset();
text += 'reset\t' + date + '\t' + date.timezoneOffset + '\n';

// Warning
// .getTime() returns the offset time after .setTimezoneOffset(offset != local)

text += '\nWarning\n\n';
// true time
text += 'time2\t' + date.getTime() + '\t(offset == local)\t' + date.timezoneOffset + '\n';
// -UTC+03:33 => -213
date.setTimezoneOffset(-213);
// false time
text += 'time3\t' + date.getTime() + '\t(offset != local)\t' + date.timezoneOffset + '\n';
// compute true time
text += 'time4\t' + (date.getTime() - (date.getTimezoneOffset() - date.timezoneOffset) * 6e4) + '\tcomputed\n';

console.log(text);

Result:

Example

time1	1511239158292
  UTC	Tue, 21 Nov 2017 04:39:18 GMT
local	Mon Nov 20 2017 20:39:18 GMT-0800 (Pacific Standard Time)	undefined
set-4	Tue Nov 21 2017 00:39:18 GMT-0800 (Pacific Standard Time)	240
set+6	Tue Nov 21 2017 10:39:18 GMT-0800 (Pacific Standard Time)	-360
set 0	Tue Nov 21 2017 04:39:18 GMT-0800 (Pacific Standard Time)	0
reset	Mon Nov 20 2017 20:39:18 GMT-0800 (Pacific Standard Time)	480

Warning

time2	1511239158292	(offset == local)	480
time3	1511280738292	(offset != local)	-213
time4	1511239158292	computed

date settimezoneoffset

Leave a Reply