微信小程序日历事件添加实现

发布于:2025-09-07 ⋅ 阅读:(20) ⋅ 点赞:(0)

微信小程序调用系统日历添加事件需要用到wx.addPhoneCalendarwx.addPhoneRepeatCalendar两个API。这两个API分别用于添加单次事件和重复事件。

添加单次日历事件

使用wx.addPhoneCalendar添加单次事件需要配置以下参数:

wx.addPhoneCalendar({
  title: '会议', // 事件标题
  startTime: 1609430400000, // 开始时间戳(毫秒)
  endTime: 1609434000000, // 结束时间戳(毫秒)
  allDay: false, // 是否全天事件
  description: '季度总结会议', // 事件描述
  location: '公司会议室A', // 事件地点
  success(res) {
    console.log('添加成功', res)
  },
  fail(err) {
    console.error('添加失败', err)
  }
})

添加重复日历事件

wx.addPhoneRepeatCalendar支持设置重复规则:

wx.addPhoneRepeatCalendar({
  title: '健身',
  startTime: 1609430400000,
  endTime: 1609434000000,
  allDay: false,
  description: '每周健身计划',
  location: '健身房',
  repeatInterval: 'week', // 重复周期:day/week/month/year
  repeatEndTime: 1640966400000, // 重复结束时间
  success(res) {
    console.log('重复事件添加成功', res)
  },
  fail(err) {
    console.error('添加失败', err)
  }
})

权限处理

调用日历API前需要处理权限问题:

wx.getSetting({
  success(res) {
    if (!res.authSetting['scope.writePhotosAlbum']) {
      wx.authorize({
        scope: 'scope.writePhotosAlbum',
        success() {
          // 用户已授权
        }
      })
    }
  }
})

完整示例代码

以下是一个完整的日历事件添加组件示例:

Page({
  data: {
    eventTitle: '',
    startTime: '',
    endTime: ''
  },
  
  // 添加单次事件
  addSingleEvent() {
    wx.addPhoneCalendar({
      title: this.data.eventTitle,
      startTime: new Date(this.data.startTime).getTime(),
      endTime: new Date(this.data.endTime).getTime(),
      allDay: false,
      success(res) {
        wx.showToast({ title: '添加成功' })
      },
      fail(err) {
        wx.showToast({ title: '添加失败', icon: 'none' })
      }
    })
  },
  
  // 添加每周重复事件
  addWeeklyEvent() {
    const endDate = new Date(this.data.endTime)
    endDate.setMonth(endDate.getMonth() + 3) // 三个月后结束
    
    wx.addPhoneRepeatCalendar({
      title: this.data.eventTitle,
      startTime: new Date(this.data.startTime).getTime(),
      endTime: new Date(this.data.endTime).getTime(),
      repeatInterval: 'week',
      repeatEndTime: endDate.getTime(),
      success(res) {
        wx.showToast({ title: '重复事件添加成功' })
      }
    })
  }
})

注意事项

  1. 时间戳需要使用毫秒格式
  2. iOS和Android系统对日历事件的处理可能有所不同
  3. 重复事件的结束时间必须晚于开始时间
  4. 部分Android系统可能不支持重复事件功能

以上代码实现了微信小程序中添加系统日历事件的基本功能,开发者可以根据实际需求进行扩展和优化。


网站公告

今日签到

点亮在社区的每一天
去签到