如何通过Google Calendar API向用户获取日期和时间?

问题描述 投票:0回答:1

我正在使用Google API在Google日历中创建一些事件。我需要从用户输入中获取日期和时间。这可能是我的逻辑问题,但我无法弄清楚。这是我的代码:

var dateTime;

app.post('/', function (req, res) {
    res.render('index');
    var date = req.body.date;  //I get date from user
    var time = req.body.time;  // I get time from user
    dateTime = date +'T'+ time+":00"; //trying to create the RFC3339 fromat
    console.log("date time: ",dateTime);
    createEvents(jwtClient);
  }); 

 var event = {    
  'start': {
      'dateTime': dateTime,
      'timeZone': 'America/Los_Angeles',
  },
  'end': {
     'dateTime': '2020-06-12T12:00:00',
     'timeZone': 'America/Los_Angeles',
  },

 'conferenceData': {
    'createRequest': {
      'conferenceSolutionKey': {
        'type': 'hangoutsMeet'
        },
     'requestId': 'iyfuted65e3ers'

    }
  },

'attendees': [
  {'email': '[email protected]'},
  {'email': '[email protected]'},
],
'reminders': {
  'useDefault': false,
  'overrides': [
    {'method': 'email', 'minutes': 24 * 60},
    {'method': 'popup', 'minutes': 10},
   ],
  },
};


 //Create Appointment
  function createEvents(auth) {
    const calendar = google.calendar({ version: 'v3', auth });
    calendar.events.insert({
        calendarId: 'primary',
        conferenceDataVersion: 1,
        resource: event,
    }, (err, res) => {
       if (err) return console.log('The API returned an error: ' + err);
         else {
        result = res.data.hangoutLink;
        console.log(result," start date: ", event.start.dateTime);

       }
    });
 }

当我在帖子部分中打印dateTime时,它是用户输入的正确日期,但在事件变量中无法识别它。我收到此错误消息:

错误:开始时间和结束时间必须都为日期或都为dateTime。

我还有另一个问题,如何增加一个小时的开始时间并将其用于结束时间?

You can see the text fields that user can enter the date and time here

javascript datetime google-calendar-api
1个回答
0
投票
  • Google Calendar事件的开始和结束时间必须按照RFC3339格式设置>
  • 您可以用new Date()检索时间
  • 如果需要检索客户端时区并将其手动更正为所需时区,则可以使用getTimeZoneOffset()
  • 我不太了解您要如何处理用户时区,但是以下两个示例显示了可能的情况:

  var now = new Date();
  Logger.log("Current time:" + now);
  var dateTime = new Date(now.getTime()).toISOString().split(".")[0];
  Logger.log(dateTime);
  var event = {    
   'start': {
      'dateTime': dateTime,
      'timeZone': 'America/Los_Angeles',
  },
   'end': {
     'dateTime': '2020-06-12T12:00:00',
     'timeZone': 'America/Los_Angeles',
  },
...

  var now = new Date();
  Logger.log("Current time:" + now);
  var offset = new Date().getTimezoneOffset();
  offset = (offset / (-60));
  if (offset < 10) {
    offset =  '0'+offset;
  }
  offset = '+' + offset + ':00';
  var dateTime = new Date(now.getTime()-new Date().getTimezoneOffset()*60*1000).toISOString().split(".")[0] + offset;
  Logger.log(dateTime);
  var event = {    
    'start': {
      'dateTime': dateTime
    },
   'end': {
     'dateTime': '2020-06-12T12:00:00-07:00'
   },
© www.soinside.com 2019 - 2024. All rights reserved.