Google Apps 脚本:从电子表格中检索日期并写入联系人

Google Apps Script: Retrieve Date from Spreadsheet and write to Contacts

使用 Google Apps 脚本,我尝试获取电子表格中写入的日期并将其作为日期字段添加到联系人中。具体来说,我似乎无法将从电子表格中读取的 javascript 日期的月份转换为 month enum that the contact.addDate method 可以使用。

var months = ContactsApp.Month.values;
var birthdate = new Date( spreadsheet_date );
var month = months[ birthdate.getMonth() ];
contact.addDate(ContactsApp.Field.BIRTHDAY, 
     month, birthdate.getDate(), birthdate.getFullYear() );

有很多方法可以解决,因为我认为开关是最简单的,但是没有单行,因为 Javascript:

中没有内置月份名称
var month = birthdate.getMonth();
switch(month){
   case 0:
      month = ContactsApp.Month.JANUARY;
      break;
   case 1:
      month = ContactsApp.Month.FEBRUARY;
      break;
   [...]
   case 11:
      month = ContactsApp.Month.DECEMBER
      break;
}

另一种模式...

var arr = [
    CalendarApp.Month.JANUARY,
    CalendarApp.Month.FEBRUARY,
    CalendarApp.Month.MARCH,
    ...
];
var month = arr[birthdate.getMonth()];

在post这里

看看我是如何解决我的另一个问题的

Google Contact "Birthday" field not showing when set from Apps Script

您需要从枚举到月份名称的映射。这将避免长的 switch 语句。这个解决方案最初是由@tehhowch 提供给我的。

var month = months[ birthdate.getMonth() ];
var monthAsInt={JANUARY:1,FEBRUARY:2,MARCH:3,APRIL:4,MAY:5,JUNE:6,JULY:7
  ,AUGUST:8,SEPTEMBER:9,OCTOBER:10,NOVEMBER:11,DECEMBER:12}[month];

作为函数;

function monthToInt(month) {
  return {JANUARY:1,FEBRUARY:2,MARCH:3,APRIL:4,MAY:5,JUNE:6,JULY:7
      ,AUGUST:8,SEPTEMBER:9,OCTOBER:10,NOVEMBER:11,DECEMBER:12}[month];
}