英文:
Google Apps Script - Date prints different to sheet than on apps editor
问题
以下是翻译好的代码部分:
function todaysDate() {
var td = new Date();
m = td.toLocaleString('default', { month: 'short' })
return (td.getDate() + " " + m ) + " " + td.getFullYear();
}
console.log(todaysDate());
如果需要其他翻译,请提供具体内容。
英文:
As we know, using TODAY() function in sheets updates to the current date every time the doc is opened. I need the date to stay constant once it is added.
So, I wrote a little code to be able to print today's date in google sheets.
function todaysDate() {
var td = new Date();
m = td.toLocaleString('default', { month: 'short' })
return (td.getDate() + " " + m ) + " " + td.getFullYear();
}
console.log(todaysDate());
This code results in 9 Mar 2023. Pic: Code + Outcome
However, the date prints correct in the GAS Project Editor on console.log, however, when added to the sheet, the result is wrong.
This is what appears in sheets 9 M03 2023. Pic: Outcome in Sheets
Appreciate any ideas on how to resolve this. Thanks for helping!
答案1
得分: 1
你可能会在使用 toLocaleString()
时遇到一些问题,你可以尝试使用 Intl.DateTimeFormat
来设置日期的特定格式,这段代码希望在表格中正确地格式化它。
function todaysDate() {
var td = new Date();
var formatter = new Intl.DateTimeFormat('en-US', { month: 'short' });
var month = formatter.format(td);
return (td.getDate() + " " + month ) + " " + td.getFullYear();
}
英文:
You might get into some problems with toLocaleString()
you can try to set a specific formatting of the date using Intl.DateTimeFormat
this code hopefully formats it correctly in sheets also.
function todaysDate() {
var td = new Date();
var formatter = new Intl.DateTimeFormat('en-US', { month: 'short' });
var month = formatter.format(td);
return (td.getDate() + " " + month ) + " " + td.getFullYear();
}
答案2
得分: 1
function todaysDate() {
var td = new Date();
var monthShortNames = ["Jan", "Feb", "Mar", "Apr", "May", "Jun",
"Jul", "Aug", "Sep", "Oct", "Nov", "Dec"
];
var m = monthShortNames[td.getMonth()];
return (td.getDate() + " " + m) + " " + td.getFullYear();
}
英文:
Try this. Clear and simple way of getting the month short name. It works, I've tested it.
function todaysDate() {
var td = new Date();
var monthShortNames = ["Jan", "Feb", "Mar", "Apr", "May", "Jun",
"Jul", "Aug", "Sep", "Oct", "Nov", "Dec"
];
var m = monthShortNames[td.getMonth()];
return (td.getDate() + " " + m) + " " + td.getFullYear();
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论