If changing date formats is something we use to do in Sheets quite often and is quite common to implement in scripts, what about google DOCS ?
There is a App script link in google DOCS and I tried to code something...but... where to start from ? I lost my orientation when it comes to do something for google DOCS.
How could I search for ####-##-## (YYYY-MM-DD) and replace it by ##/##/#### (DD/MM/YYYY) ? I know how to do it in Sheets. But Docs ?
No idea !
I don't even know if it's possible :D
Will you be able to help me ?
CodePudding user response:
Here is an example of replacing dates YYYY-MM-DD to DD-MM-YYYY. I simply run from script editor but it could be linked to menu option or button.
Note however, month and day have to be in the form of 2 digits 01 for January, 01 for the first day of the month.
function convertDates() {
try {
let doc = DocumentApp.getActiveDocument();
let body = doc.getBody();
let found = body.findText('(\\d{2,4}-?){3}');
let date1 = null;
while( found ) {
let text = found.getElement().asText();
if( found.isPartial() ) {
let start = found.getStartOffset();
let end = found.getEndOffsetInclusive();
date1 = text.getText().substring(start,end 1);
}
else {
date1 = text.getText();
}
let date2 = date1.split("-");
date2 = date2[2] '/' date2[1] '/' date2[0];
text.replaceText(date1,date2);
found = body.findText('(\\d{2,4}-?){3}',found);
}
}
catch(err) {
console.log(err)
}
}
Reference
CodePudding user response:
function myfunk() {
let r = DocumentApp.getUi().prompt("Enter 4 digit year, 2 digit month, 2 digit date", "yyyy/MM/dd", DocumentApp.getUi().ButtonSet.OK_CANCEL);
if (r.getSelectedButton() == DocumentApp.getUi().Button.OK) {
let t = r.getResponseText().split("\/");
let d = Utilities.formatDate(new Date(t[0], Number(t[1] - 1), t[2]), Session.getScriptTimeZone(), "dd/MM/yyyy");
DocumentApp.getUi().showModelessDialog(HtmlService.createHtmlOutput(d),"dd/MM/yyyy");
}
}