Google Apps Script – 日期在表格中与应用编辑器中不同。

huangapple go评论85阅读模式
英文:

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();
} 

huangapple
  • 本文由 发表于 2023年3月9日 20:12:43
  • 转载请务必保留本文链接:https://go.coder-hub.com/75684457.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定