Google脚本中的序数日期格式(th,rd,st,nd)

时间:2018-05-26 00:17:19

标签: javascript google-apps-script google-sheets date-formatting ordinal

我在这里到处寻找一个简单的功能,将日期(在我的情况下,由Google表格给出)转换为合同中使用的序数格式:

即。 2018年5月25日

有一个人提出这个问题而另一个人将其标记为副本,然后提到了另一个根本没有回答他的问题的答案!所以对于那些需要这个的人来说 - 这里有一个简单的功能:

function ordinal(date) {
  var d = date.getDate();
  var month = new Array ();
  month[0] = "January";
  month[1] = "February";
  month[2] = "March";
  month[3] = "April";
  month[4] = "May";
  month[5] = "June";
  month[6] = "July";
  month[7] = "August";
  month[8] = "September";
  month[9] = "October";
  month[10] = "November";
  month[11] = "December";

  var m = month[date.getMonth()];
  var y = date.getYear();
  return d + (d > 0 ? ['th', 'st', 'nd', 'rd'][(d > 3 && d < 21) || d % 10 > 3 ? 0 : d % 10] : '') + " day of " + m +", " + y;
}

1 个答案:

答案 0 :(得分:1)

通常,开发人员对平台的新手最终会重新发明轮子;实施已经提供的逻辑(从经验谈起)。没有用于添加这些后缀(st,nd,rd,th)的现成解决方案,但是,在您的情况下,您可以利用Utilities.formatDate()方法使事情变得更容易:

function getOrdinal(date) {
    var d = date.getDate(),
        suffix = ['th', 'st', 'nd', 'rd'][(d > 3 && d < 21) || d % 10 > 3 ? 0 : d % 10];

    return Utilities.formatDate(date, Session.getScriptTimeZone(), "d'" + suffix + " day of' MMMM, yyyy");
}

一些建议,总是以规范来源开始搜索。这需要一段时间,但如果您打算定期使用Google Apps脚本(或任何语言),那么最好熟悉官方文档和参考资料。

Here's a link to the official Apps Script Reference Documentation.

相关问题