Jump to content

User:Splarka/timestamplocalizer.js

From Wikipedia, the free encyclopedia
Note: After saving, you have to bypass your browser's cache to see the changes. Google Chrome, Firefox, Microsoft Edge and Safari: Hold down the ⇧ Shift key and click the Reload toolbar button. For details and instructions about other browsers, see Wikipedia:Bypass your cache.
// var autoLocalTimeStamps = false; 
// importScript('User:Splarka/timestamplocalizer.js');

// ----------------------------------------------------------
// START Timestamp localizer by Splarka (experimental)
// ----------------------------------------------------------
// This crazy script iterates over all text nodes in the 
// content area and attempts to switch signature-generated
// UTC timestamps with a version in your local time.

addOnloadHook(function() {
  if(mw.config.get('wgAction') == 'edit' || mw.config.get('wgAction') == 'submit') return //DO NOT WANT
  if(window.autoLocalTimeStamps=='true') {
    //autoload
    localTimeStamps();
  } else {
    //give a button instead
    mw.util.addPortletLink('p-cactions','javascript:localTimeStamps()','Localize timestamps','ca-local','This will attempt to convert all timestamps on the page to your local time');
  }
});

function localTimeStamps() {
  findTextNodes(changeTimeStamp,document.getElementById('bodyContent'));
}

function changeTimeStamp(obj) {
  var pattern = /\d\d\:\d\d\, \d{1,2} \w{1,30} \d{4} \(UTC\)/;
  while(obj.nodeValue.search(pattern)!=-1) {
    var dat = ''+ obj.nodeValue.match(pattern);
    var hour = '' + dat.match(/\d\d\:\d\d\, /)
    hour = hour.replace(/\,/,'');
    dat = dat.replace(/\d\d\:\d\d\, /,'');
    dat = dat.replace(/ \(UTC\)/,' '+ hour + ' UTC');
    var ts = new Date(dat);
    ts.setTime(ts.getTime());
    obj.nodeValue = obj.nodeValue.replace(pattern,ts.toString());
  }
}

// General text-node finder/magic/functioner
// * iterates over childnodes of obj
// * if obj is text, perform func() on it
// * if obj has childnodes, call self recursively
function findTextNodes(func,obj) {
  if (obj.nodeType == 3) {
    func(obj);
  }
  var i=0;
  while(obj.childNodes[i]) {
    findTextNodes(func,obj.childNodes[i]);
    i++;
  }
}

// ----------------------------------------------------------
// END Timestamp localizer
// ----------------------------------------------------------