Insert contact's birthday using DatePicker card service and App Script Contact API

Updated: June 1, 2020

DatePicker is a very useful date picker card service. You can use this control for allowing user to select date in the form. It works well in mobile application.

1.Add Date Picker card service

const generalSection = CardService.newCardSection().setHeader("General Information");
const dateInput = (CardService as any)
      .newDatePicker()
      .setFieldName("text_input_form_input_birthday")
      .setTitle("Birthday");
generalSection.addWidget(dateInput);
builder.addSection(generalSection);

2.Parse Date Picker for inserting birthday using Appscript Contact API

  • Because Contact API uses ContactsApp.Month enum so I need to define an enum for mapping from month to it
const months = ContactsApp.Month;
const monthToEnum = {
  'January': months.JANUARY,
  'February': months.FEBRUARY,
  'March': months.MARCH,
  'April': months.APRIL,
  'May': months.MAY,
  'June': months.JUNE,
  'July': months.JULY,
  'August': months.AUGUST,
  'September': months.SEPTEMBER,
  'October': months.OCTOBER,
  'November': months.NOVEMBER,
  'December': months.DECEMBER
};
monthEnum = monthToEnum[birthdayMonth];
  • And then I need to get timezone ID and year, month, day of birthday
const userTimezoneId = e.userTimezone.id;
let monthEnum = null;
let birthdayDay = null;
let birthdayMonth = null;
let birthdayYear = null;

if (birthday) {
  const msSinceEpoch = birthday.msSinceEpoch;

  birthdayYear = Utilities.formatDate(
    new Date(msSinceEpoch), userTimezoneId, "yyyy");
  birthdayMonth = Utilities.formatDate(
    new Date(msSinceEpoch), userTimezoneId, "MMMM");
  const birthdayDay = Utilities.formatDate(
    new Date(msSinceEpoch), userTimezoneId, "dd");
  const months = ContactsApp.Month;
  const monthToEnum = {
    'January': months.JANUARY,
    'February': months.FEBRUARY,
    'March': months.MARCH,
    'April': months.APRIL,
    'May': months.MAY,
    'June': months.JUNE,
    'July': months.JULY,
    'August': months.AUGUST,
    'September': months.SEPTEMBER,
    'October': months.OCTOBER,
    'November': months.NOVEMBER,
    'December': months.DECEMBER
  };
  monthEnum = monthToEnum[birthdayMonth];
}

3. Insert contact using Contact API
Finally, you insert contact using Contact API

contact.addDate(ContactsApp.Field.BIRTHDAY as any,
monthEnum, Number(birthdayDay), Number(birthdayYear))
<