Reputation: 55
Using Google Apps script, I'm trying to take a date written in a spreadsheet and add it as a date field to a Contact. Specifically, I cannot seem to convert the month of the javascript date read from the spreadsheet into a month enum that the contact.addDate method can use.
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() );
Upvotes: 0
Views: 1405
Reputation: 1943
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];
as a function;
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];
}
Upvotes: 0
Reputation: 109
See how I'm doing it in this post of a different question I have, here
Google Contact "Birthday" field not showing when set from Apps Script.
You need a mapping from the enum to the month name. This will avoid the long switch statement. This solution was initially provided to me by @tehhowch.
Upvotes: 0
Reputation: 5051
another pattern...
var arr = [
CalendarApp.Month.JANUARY,
CalendarApp.Month.FEBRUARY,
CalendarApp.Month.MARCH,
...
];
var month = arr[birthdate.getMonth()];
Upvotes: 1
Reputation: 3778
There are lots of ways to approach, as I see a switch is the easiest, there's no one-liner though, as there's no month name built into 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;
}
Upvotes: 1