phonegap 3 date shows the wrong time - android

I'd like to get the system-time inclusive the milliseconds. Therefore I use this method to get the system-time:
1)
var dt = JSON.stringify(new Date());
The dateToString method only returns the date-format with minutes, not the seoonds and milliseconds
2)
navigator.globalization.dateToString(
new Date(),
function (date) { alert('date: ' + date.value + '\n'); },
function () { alert('Error getting dateString\n'); },
{ formatLength: 'short', selector: 'date and time' }
);
My system-time is 13:07
returns
11:07:44...
returns
13:07
Is it possible to get the seconds and milliseconds from the dateToString method?

JavaScript's Date() has a lot of methods that can help you, like getMilliseconds() which will return....the number of milliseconds. There is also getMinutes, getSeconds, etc. See the full list here:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date

Related

How to compare date and time in kotlin android?

I have an app on the PlayStore and I am building a feature where the user will not see ads more than a specific number in one day.
I am thinking about comparing the current date and time to the previously saved one but haven't find a proper way to do that.
How can I compare date and time to know if 24 hours have passed or not?
Some posts that I found but not helpful:
medium.com
stackoverflow
stackoverflow
tl;dr
[This Answer uses Java syntax. You’ll have to translate to Kotlin syntax.]
if
(
Duration // Represents elapsed time on the scale of hours-minutes-seconds.
.between( // Calculates elapsed time between two points in time.
Instant.parse( "2021-03-23T15:30:57.013678Z" ) , // Last moment when an ad was show.
Instant.now() // Current moment.
) // Returns a `Duration` object.
.toHours() // Extract total number of whole hours from the `Duration` object.
>= 24L // Test if equals-to or greater-than 24 hours.
)
{ show ad }
java.time
You asked:
… know if 24 hours have passed or not?
Use the modern java.time classes defined in JSR 310. The java.time classes are built into Android 26 and later. Most of the functionality is available in earlier Android using the latest tooling’s “API desugaring“.
Instant adShown = Instant.parse( "2021-03-23T15:30:57.013678Z" ) ;
Instant now = Instant.now() ;
Duration d = Duration.between( adShown , now ) ;
long hoursSinceAdShown = d.toHours() ;
if( hoursSinceAdShown >= 24L ) { … show ad }
Record your next ad-showing as text in standard ISO 8601 format.
String output = Instant.now().toString() ;
2021-03-23T15:30:57.013678Z
Your Question asked for two different things:
Once per day
Every 24 hours
The first involves a calendar, dates, and a time zone. The second does not. I showed you code for the second.
You can use a scheduled executor service to trigger from a background thread the next showing of an ad at a specific moment. Search Stack Overflow to learn more as this has been covered many times already.
Use this code to check the current date, Yesterday or Particulardate. Pass Epoch time to this method
// input format (we get a value as Epoch)
private val inputFormat = SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'")
private val outputFormat = SimpleDateFormat("MMM dd")
// have to pass the time value as Epoch time.
private fun calculateDateMonth(time: String): String {
var returnValue = ""
val dateTime = DateTime((time.toLong()) * 1000L)
val inputTime = inputFormat.parse(dateTime.toString())
val convertDateMonth = outputFormat.format(inputTime!!)
val timeInMilliseconds = outputFormat.parse(convertDateMonth)!!
val mTime: Calendar = Calendar.getInstance()
mTime.setTimeInMillis(timeInMilliseconds.time)
val now = Calendar.getInstance()
returnValue = when {
now[Calendar.DATE] == mTime[Calendar.DATE] // check isToday
now[Calendar.DATE] - mTime[Calendar.DATE] == 1 // check Yesterday
else -> convertDateMonth // Month and Date
}
return returnValue
}

FCM in android notification payload , event_time

i want to make the notification push on like maybe 5 minute after i run this http function. delete the event_time from the jsaon of notification i will receive the push notification that have timeline now, but if i hard code the event_time the time will show 50 year ago since epoch time , event i put 999 for the year it just increase by 2 year . i dint get it at all. then found Timestapm format in google and firebase so use it and the android got error whil parsing the json payload said cant fine field something . have any idea to format the Zulu RC399 time format?
pp.get('/sendCloudMessageReminderActivation', async (req, res) => {
const x = req.query.userUID;
const xstr = String(x);
const zxcv = admin.firestore().collection('user').doc(xstr);
const xoxo = await zxcv.get();
var today = new Date();
// today.setHours(today.getHours()+1);
today.setHours(today.getHours()+8);
// today.setFullYear(today.getFullYear()+50);
var xoxocode;
console.log(today+'saya saya sebelum cagbge');
// today = ISODateString(today);
const timestamp = admin.firestore.Timestamp.fromDate(today);
console.log(timestamp.nanoseconds +'siniiiiiiiiiiiiiiiiiiiii');
if (xoxo!==null) {
xoxocode= await xoxo.data().cloudMessagingToken;
const message = {
notification: {
title: 'your account is still in active state',
body: 'Tap here to check it out!'
},
android:{
priority:'high',
// important : 'MAX',
notification:{
notification_priority: "PRIORITY_MAX",
event_time: timestamp,// when ever i cahnge this event use ZULU RC339 format i still give my 50 year ago notification. i did my research but cant figure out how to do this ,
default_sound: true,
// notification_priority: PRIORITY_MAX
}
},
token: xoxocode
};
// res.status(200).send('authorized');
const respondfrommesage = admin.messaging().send(message);
console.log(respondfrommesage);
res.status(200).send('message send notification');
}
res.end();
});
Zulu is not a time format. It's a time zone. Zulu is just another name for UTC.
As per this article:
Another name for UTC Time is "Zulu" or "Z Time."
Now, about the timestamp value. If you are creating a Date object and use milliseconds or nanoseconds property of a date, it will always give you the difference in respective property type (mills/nano),
From the time you created the instance and starting time of UNIX which is 1 January 1970.
It has been 50 years as of 1st Jan, 2020. Hence the 50 year difference in the event_time.
If you have any other doubts let me know.

Phonegap: local notification repeat every Sunday of the week?

I'm trying to implement the Phonegap local notification in my project.
I'm using this plugin:
de.appplant.cordova.plugin.local-notification-custom
I have installed the plugin and tested it and it works fine.
I tested it with this code and it works fine:
cordova.plugins.notification.local.schedule({
id : 1,
title : 'I will bother you every minute',
text : '.. until you cancel all notifications',
sound : null,
every : 'minute',
autoClear : false,
at : new Date(new Date().getTime() + 10*1000)
});
The above notification will run every minute and work fine.
Now, I need to set a local notification that will only run on every Sunday and every week.
I came across something like this but when tested it, it does nothing:
cordova.plugins.notification.local.schedule({
id: 1,
title: "Test...",
text: "Test...",
sound: null,
every: 'week',
at: sunday_16_pm
});
I don't even know if at: sunday_16_pm is correct or not!
Could someone please advice on this issue?
Thanks in advance.
EDIT:
After searching for hours and finding nothing, I just came across this documentation:
https://github.com/katzer/cordova-plugin-local-notifications/wiki/04.-Scheduling
They have a sample code that says:
Schedule Repeatedly
cordova.plugins.notification.local.schedule({
text: "Delayed Notification",
firstAt: monday,
every: "day",
icon: "file://img/logo.png"
}, callback);
But what is monday?!? is that a variable? And if so, how do you create that variable?
I don't understand why people write documentation as if no one else would want to read/understand them!!
Another edit:
I found this which explains exactly what i'm trying to do but I'm not using ionic and never have. So I don't understand the code that is provided there at all!
https://www.joshmorony.com/getting-familiar-with-local-notifications-in-ionic-2/
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.

Titanium Change event not firing the first time with picker

I am making an iOS and Android app using Titanium Classic. I am fairly new to Titanium but I have some experience using Javascript. The app will have a window where the user and select from a picker an amount of time in hours and minutes. The selection will be saved and be used later to send a notification to the user that the time they selected is up. I am currently using Titanium's picker function with the type of "count down timer." However, I am having trouble getting the change event to work when the user selects a different time. It also will show the last selected time when I try going to a different window and entering the timer window again.
My question is how can I get the change event to fire the first time the user selects a different number?
In follow up to my question, is there a better way to save the picker selection for later use?
Here is the code for the picker:
var hours = 0;
var minutes = 1;
var win = Ti.UI.createWindow({
backgroundColor: '#A6B97B',
layout: 'horizontal'
});
var picker = Ti.UI.createPicker({
type:Ti.UI.PICKER_TYPE_COUNT_DOWN_TIMER,
top:2,
width: '50%',
height: '20%'
});
picker.addEventListener("change", function(e) {
Ti.App.Properties.setInt('countDownDuration', e.countDownDuration);
if (e.countDownDuration >= 3600000)
{
hours = Math.floor(Ti.App.Properties.getInt('countDownDuration')/3600000);
minutes = Math.floor(Ti.App.Properties.getInt('countDownDuration')/60000 - (hours*60));
}
else {
minutes = Math.floor(Ti.App.Properties.getInt('countDownDuration')/60000);
hours = 0;
}
});
var doneBtn = Ti.UI.createButton({
title : 'Get Value',
height : '15%',
width : '30%'
});
doneBtn.addEventListener('click', function() {
// get value
if(hours > 0){
alert('You set the time estimate to ' + hours + ' hours and ' + minutes+ ' minutes');
}
else {
alert('You set the time estimate to ' + minutes + ' minutes');
}
});
If anyone has any advice on how to get the change event to fire the first time, I would really appreciate it. Also, if you know a better way to accomplish saving data from the picker for use later, that would be helpful as well.
Thanks!
Jessica

check current time between time interval android

I want to create an app that will allow the user to check whether or not the current time falls between a specified time interval. More specifically, I created a sql table using sqllite program, with the table specifying an end time and a start time for each record. The problem is that the type of data each field can be is limited to text, number, and other type other than a datetime type. So, how would I be able to check if the current time is between the start and end time since the format of time is in h:mm and not just an integer value that I could just do less than or greater than? Do I have to convert the current time to minutes?
You should be able to do the comparison even if time is not stored in the datetime type, here is a link that explains the conversion from string to time.
If that doesn't work, convert the time to seconds (int) and calculate the difference.
Try this. You can save and retrieve your time as String:
String to long: String.valueOf()
long to String: Long.valueOf()
Then, you use this procedure to check time:
//Time checker
private boolean timeCheck(long startTimeInput, long endTimeInput) {
long currentTime = System.currentTimeMillis();
if ((currentTime > startTimeInput) && (currentTime < endTimeInput)) {
return true;
} else {
return false;
}
}
And in your main program check it like this:
//You kept the times as String
if (timeCheck(Long.valueOf(start), Long.valueOf(end))) {
//it is in the interval
} else {
//not in the interval
}
I hope it helps.

Categories

Resources