请求修改Adobe InDesign JS脚本适配英式日期格式(dd/MM/yyyy)
修改Adobe InDesign脚本适配英式日期格式转换
需求:将英式日期格式(dd/MM/yyyy,如25/12/2022)转换为“日 月份全称 年”格式(如25 December 2022),原脚本仅支持美式日期(mm/DD/yyyy),需调整适配英式格式。
修改思路
原脚本直接用new Date(date)解析日期时,会默认把/分隔的日期识别为美式格式,导致英式日期解析错误。需要手动拆分日期字符串,交换日和月的位置后再创建日期对象,确保月份解析正确。
修改后的完整脚本
//DESCRIPTION: Convert date format - finds 25/12/2022 and replace it with 25 December 2022 #target indesign; /* by Oleh Melnyk at 5 April 2017 modified to support dd/MM/yyyy (British date format) */ //> START OF doUndoWraper if (parseFloat(app.version) < 6) // "app.version < 6" if it's running under an earlier version than CS4, as earlier versions don't support "Undo" in scripts doUndoWrapper(); else app.doScript(doUndoWrapper, ScriptLanguage.JAVASCRIPT, undefined, UndoModes.ENTIRE_SCRIPT, "Change Date Format"); //< END OF doUndoWraper function doUndoWrapper(){ function toUnique(a, b, c) { //array,placeholder,placeholder b = a.length; while (c = --b) while (c--) a[b] !== a[c] || a.splice(c, 1); return a // not needed ;) } function convertDateFormat(dateStr){ // 拆分英式日期字符串:dd/MM/yyyy const [day, month, year] = dateStr.split('/'); // JS的Date月份为0-11,需将月份值减1 var objDate = new Date(year, month - 1, day); var monthName = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"]; return ("0" + objDate.getDate()).slice(-2) + " " + monthName[objDate.getMonth()] + " " + objDate.getFullYear(); } app.findGrepPreferences = app.changeGrepPreferences = NothingEnum.nothing; // clear settings app.findChangeGrepOptions.includeLockedLayersForFind = false; // search in Locked Layers app.findChangeGrepOptions.includeLockedStoriesForFind = false; // search in Locked Stories app.findChangeGrepOptions.includeHiddenLayers = false; // search in HiddenLayers app.findChangeGrepOptions.includeMasterPages = false; // search in Master Pages app.findChangeGrepOptions.includeFootnotes = true; // search in Footnotes app.findGrepPreferences.findWhat = "\\d{2}\\/\\d{2}\\/\\d{4}"; var whereToSearch = app.activeDocument; // default - search in entire document var foundPrep = whereToSearch.findGrep(); var foundElements = []; for(var x = 0; x < foundPrep.length; x++){ foundElements.push(foundPrep[x].contents); } var foundUnique = toUnique(foundElements); for(var i = 0; i < foundUnique.length; i++){ var option = foundUnique[i]; app.findGrepPreferences.findWhat = option; app.changeGrepPreferences.changeTo = convertDateFormat(option); whereToSearch.changeGrep(); app.findGrepPreferences = app.changeGrepPreferences = NothingEnum.nothing; // clear find what and change to field } }
关键修改点
- 重写
convertDateFormat函数:手动拆分英式日期为日、月、年,按年, 月-1, 日的顺序传入Date构造函数(适配JS日期的0索引月份规则)。 - 更新脚本描述,明确标注支持英式日期格式。
内容的提问来源于stack exchange,提问作者pt-t
相关产品推荐
相关产品推荐

