Phonegap: local notification repeat every Sunday of the week?

为君一笑 提交于 2019-12-06 02:40:16

I don't know about those variables sunday_16_pm or monday either, but you can use your own variable with firstAt.

First of all you have to find the timestamp for sunday_16_pm to tell this plugin that the repeating should start on sunday afternoon.

In order to find this timestamp (that I suppose this should be done dynamically), I wrote the function getDayMillDiff to calculate the time-difference between now and sunday. Afterwards this difference is used to obtain the desired sunday_16_pm.

function getDayMillDiff(refday){
    var days = {
        monday: 1,
        tuesday: 2,
        wednesday: 3,
        thursday: 4,
        friday: 5,
        saturday: 6,
        sunday: 0
    };
    if(!days.hasOwnProperty(refday))throw new Error(refday+" is not listed in "+JSON.stringify(days));
    var curr = new Date();
    var triggerDay = days[refday];
    var dayMillDiff=0;
    var dayInMill = 1000*60*60*24;
    // add a day as long as refday(sunday for instance) is not reached
    while(curr.getDay()!=triggerDay){
        dayMillDiff += dayInMill;
        curr = new Date(curr.getTime()+dayInMill);
    }
    return dayMillDiff;
}

var today = new Date();

// how many days are between current day (thursday for instance) to sunday, add this difference to this sunday variable
var sunday = today.getTime() + getDayMillDiff("sunday");

// convert timestamp to Date so that hours can be adjusted
var sunday_16_pm = new Date(sunday);
sunday_16_pm.setHours(16,0,0);

// now we can use sunday_16_pm to schedule a notification showing at this date and every past week 
cordova.plugins.notification.local.schedule({
    id: 1,
    title: "Test...",
    text: "Test...",
    every: 'week',
    firstAt: sunday_16_pm
});

One more example:

To test getDayMillDiff for other days than sunday, you can simply pass the string "monday" onto it (please use always a name listed within the variable days in getDayMillDiff):

var today = new Date();
var monday = today.getTime() + getDayMillDiff("monday");

var monday_10_am = new Date(monday);
monday_10_am.setHours(10,0,0);

cordova.plugins.notification.local.schedule({
    id: 1,
    title: "Test...",
    text: "Test...",
    every: 'week',
    firstAt: monday_10_am
});

Hope it helps.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!