Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Replace all relative time with local times in Stack Exchange sites
// ==UserScript==
// @name ShowLocalTime
// @namespace dannyhajj
// @description Show the local time instead of absolute time
// @include http://*askubuntu.com/*
// @include http://*mathoverflow.net/*
// @include http://*onstartups.com/*
// @include http://*serverfault.com/*
// @include http://*stackapps.com/*
// @include http://*stackexchange.com/*
// @include http://*stackoverflow.com/*
// @include http://*superuser.com/*
// @version 1.0.0
// @grant none
// ==/UserScript==
function with_jquery(f) {
var script = document.createElement("script");
script.type = "text/javascript";
script.textContent = "(" + f.toString() + ")(jQuery)";
document.body.appendChild(script);
};
with_jquery(function ($) {
$(document).ready(function () {
/*
* Select all relative times and loop each of them and replace them
* by the browser's local date time string
*/
$('.relativetime').one('mouseover', function() {
var current_value = this.innerHTML;
/*
* Replace the space in the date time string by a T, so it matches
* the ECMAScript specification
* http://www.ecma-international.org/ecma-262/5.1/#sec-15.9.1.15
* The date string is taken from the title
*/
var date_string = this.title.replace(/\s/g, 'T');
// Convert the date string to a Date object
var date_time = new Date(date_string);
// Write the date in the Stackexchange format MON D YY at H:M
this.innerHTML = formatDate(date_time);
// Replace the title value with the HTML of the element
this.title = current_value;
});
/**
* Formats a date object to YYYY-MM-DD HH:mm:ss
*
* @param {Date} date A date object to format as a string
*
* @return {string} The formated string
*/
function formatDate(date) {
// Get Full year of the date
var year = date.getFullYear();
/*
* When any of all of the next values are a single digit,
* a 0 is added to left
* The month value is incremented by 1, since Date.prototype.GetMonth()
* returns 0 for Jan, 1 for Feb, etc.
*/
var month = padByAZero(date.getMonth() + 1);
var day = padByAZero(date.getDate());
var hours = padByAZero(date.getHours());
var minutes = padByAZero(date.getMinutes());
var seconds = padByAZero(date.getSeconds());
// return the date string with the YYYY-MM-DD HH:mm:ss format
var date_string = year + '-' + month + '-' + day
+ ' ' + hours + ':' + minutes + ':' + seconds;
return date_string;
}
/**
* Make sure a number is 2 digits. Example that
* 1 becomes 01, 10 stays 10. Careful that the return value
* is always 2 digits. So padByAZero(201) returns the string "01"
*
* @link http://stackoverflow.com/a/8169833/535122
*
* @param {int} value The value to pad
*
* @return {string} A digits string
*/
function padByAZero(value) {
return ('0' + value).slice(-2);
}
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.