已申请日历权限,但是无法读取显示为空,具体demo如下:
import { calendarManager } from '@kit.CalendarKit';
const TAG = "[SystemCalendarManager]"
export function getThisDayStart(date: Date = new Date()): Date {
let dateTime = new Date(date);
dateTime = new Date(dateTime.setHours(0));
dateTime = new Date(dateTime.setMinutes(0));
dateTime = new Date(dateTime.setSeconds(0));
dateTime = new Date(dateTime.setMilliseconds(0));
return dateTime
}
/**
* 获取当日终点
* @param date 查询的日期
*/
export function getThisDayEnd(date: Date = new Date()): Date {
let dateTime = new Date(date);
dateTime = new Date(dateTime.setHours(23));
dateTime = new Date(dateTime.setMinutes(59));
dateTime = new Date(dateTime.setSeconds(59));
dateTime = new Date(dateTime.setMilliseconds(999));
return dateTime
}
/**
* 获取日历内容
* @param showDate 日期
* @param context
* @returns
*/
export async function getSystemCalendarEvents(showDate: Date, context: Context): Promise<void> {
console.log(TAG, "getSystemCalendarEvents", showDate.toLocaleString())
if (canIUse("SystemCapability.Applications.CalendarData")) {
console.log(TAG, "canIUse", "SystemCapability.Applications.CalendarData")
try {
let calendarMgr = calendarManager.getCalendarManager(context);
let calendar = await calendarMgr.getCalendar()
let filter = calendarManager.EventFilter.filterByTime(
getThisDayStart(showDate).getTime(),
getThisDayEnd(showDate).getTime()
);
let events: Array<calendarManager.Event> = await calendar.getEvents(filter);
console.warn(TAG, "getSystemCalendarEvents", JSON.stringify(filter), JSON.stringify(events))
} catch (err) {
console.error(TAG, "getSystemCalendarEvents", JSON.stringify(err))
}
}
return
}
最终出来的结果为:
[SystemCalendarManager] getSystemCalendarEvents {} []
calendar获取日程事件是有权限限制的,只能获取本应用创建的日程事件,(系统日历程序权限更高,只有系统日历可以获取所有的日程事件)。