User:RoyZuo/ISO8601Converter.js

From Wikimedia Commons, the free media repository
Jump to navigation Jump to search
Note: After saving, you have to bypass your browser's cache to see the changes. Internet Explorer: press Ctrl-F5, Mozilla: hold down Shift while clicking Reload (or press Ctrl-Shift-R), Opera/Konqueror: press F5, Safari: hold down Shift + Alt while clicking Reload, Chrome: hold down Shift while clicking Reload.
// <nowiki>
/*
  script to convert dd mon yyyy to yyyy-mm-dd

  skeleton
  
  Original author of Catcheck.js: [[User:Lupo]], September 2008
  Derived from [[MediaWiki:Botcheck.js]]
  License: Quadruple licensed GFDL, GPL, LGPL and Creative Commons Attribution 3.0 (CC-BY-3.0)
  
  author of MediaWiki:RemoveIncomplete.js: 4nn1l2
  
  converter by chatgpt and RoyZuo
*/
/*global $:false, wgNamespaceNumber:false, wgAction:false*/
/*jshint curly:false*/
	$(document).ready(function () {
		'use strict';

		var inputText = document.getElementById ('wpTextbox1');
		if (!inputText) return;
		
		// Call the function and get the converted text
		const finalText = replaceDatesInText(inputText);

		// Remove any whitespace from beginning and end
		finalText.value = $.trim( finalText.value || "" );

		// Set edit summary
		var add = "Converted dates to yyyy-mm-dd";
		var summary = document.getElementById ('wpSummary');
		if (!summary) return;
		var val = $.trim( summary.value || "" );
		if (val.indexOf(add) !== -1) return;
		summary.value = (val.length === 0) ? add : val + " " + add;
		document.editform.wpMinoredit.checked = true;
		document.editform.wpDiff.click();
	});

// Function to replace date occurrences in the text
function replaceDatesInText(text) {
  const dateRegex = /(\d{2}) (\w{3}) (\d{4})/g;

  // Replace each date occurrence with the converted format
  const convertedText = text.replace(dateRegex, (match, day, month, year) => {
    const monthNumber = getMonthNumber(month);
    const paddedDay = day.padStart(2, "0");
    const paddedMonth = monthNumber.padStart(2, "0");
    return `${year}-${paddedMonth}-${paddedDay}`;
  });

  return convertedText;
}

// Function to get month number from month name
function getMonthNumber(monthName) {
  const monthMap = {
    Jan: "01",
    Feb: "02",
    Mar: "03",
    Apr: "04",
    May: "05",
    Jun: "06",
    Jul: "07",
    Aug: "08",
    Sep: "09",
    Oct: "10",
    Nov: "11",
    Dec: "12",
  };

  return monthMap[monthName];
}
// </nowiki>