How to get global date and time in android? - android

In my application some functionality get closed after 9:00 PM. Its working fine if date setting of device is auto updated. But suppose right now its 10:00 pm and user changed the time 10:00 Pm to 08:00 Pm then my code is working. I want to avoid that thing.

Get the system time in UTC (Universal Coordinate Time). This answer gives it in more detail
DateFormat df = DateFormat.getTimeInstance();
df.setTimeZone(TimeZone.getTimeZone("gmt"));
Calendar cal = df.getCalendar();
int hour = cal.get(Calendar.HOUR_OF_DAY);
if (hour > 21 && hour < 9) // or 9:00pm in your time-zone converted to gmt...
{
// Do something, or don't do something
}

you have to use the external time service like this one. anything else like System.currentTimeMillis() or new Date() can be "hacked" by user

Related

Is it possible to set a specific date with the Alarm Clock?

this is how I set my alarm clock:
//all this inside a onClickListener
Calendar cal = Calendar.getInstance();
cal.set(Calendar.DAY_OF_MONTH, 30);
cal.set(Calendar.MONTH, 8);
cal.set(Calendar.YEAR, 2020);
Intent intent = new Intent(AlarmClock.ACTION_SET_ALARM);
intent.putExtra(AlarmClock.EXTRA_HOUR, Integer.parseInt(str1));
intent.putExtra(AlarmClock.EXTRA_MINUTES, Integer.parseInt(str2));
intent.putExtra(AlarmClock.EXTRA_MESSAGE, title.getText().toString());
intent.putExtra(AlarmClock.EXTRA_DAYS, cal.get(Calendar.DAY_OF_MONTH));
intent.putExtra(AlarmClock.EXTRA_SKIP_UI, true);
startActivity(intent);
All this set very well the app alarm clock on my device regarding the time, but not for the date.
Example:
Current time: 12:00 Monday
Time from my code: 13:00 Saturday
The alarm clock sets to play (the ringtone) in 1 hour
Current time: 12:00 Monday
Time from my code: 11:00 Tuesday
The alarm clock sets to play (the ringtone) in 25 hours
I dont know how to use in particular this line of code:
intent.putExtra(AlarmClock.EXTRA_DAYS, cal.get(Calendar.DAY_OF_MONTH));
Thanks in advance
You cannot set the an alarm for a specific date with an AlarmClock provider.
AlarmClock.EXTRA_DAYS is for repeating alarms. You could use something like Calendar.SUNDAY and it would ring every Sunday.
If you want more control over an alarm, you have to program it yourself. Look into the AlarmManager class. It allows you to schedule your application to be run at some point in the future.

How far (and why!) do Android alarms execute in the past?

I have had several frustrations with setting alarms in Android. I have tried setting repeating/non-repeating alarms and exact/inexact alarms but it does not matter, if the alarm is ever set for a time in the past, it executes as soon as it is set. I have tested this as far back as setting an alarm for 5 hours in the past and is still executes immediately.
For example:
The time is 7 AM and I set an alarm to execute at 2 AM. This is obviously meant for the next time the clock reads 2:00 AM but it does not matter, the alarm goes off at 7 AM, right after it is set.
The code below should select a random time between 1:00 AM and 3:59 AM to set/execute the alarm for the next calendar day and then the logic circles back around to set itself again after execution. The alarm will execute repeatedly, forever.
int randomHour = new Random().nextInt((3 - 1) + 1) + 1;
int randomMinute = new Random().nextInt((59 - 1) + 1) + 1;
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(System.currentTimeMillis());
calendar.set(Calendar.HOUR_OF_DAY, randomHour);
calendar.set(Calendar.MINUTE, randomMinute);
calendar.set(Calendar.SECOND, 0);
calendar.add(Calendar.DAY_OF_MONTH, 1);
alarmManager.setExact(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), pendingIntent);
Questions:
At what point does Android stop executing alarms in the past?
Is there any way to stop this?
"This is obviously meant for the next time" Does not work for computers, they will do exactly what you tell them to do.
calendar.getTimeInMillis() returns the number of milliseconds since January 1, 1970 at 00:00:00 GMT. You need to specify not just the time but also the date that you want the alarm to go off. Instead you are always calling calendar.add(Calendar.DAY_OF_MONTH, 1); (the first day of the current month)

Android getRelativeTimeSpanString not working

I am working on notifications and I need to display the time-> An action was performed in a way similar to ("5 seconds ago","12 mins ago","1 week ago" etc.)
This is the code I am using
long now = System.currentTimeMillis();
String datetime1 = "06/12/2015 03:58 PM";
SimpleDateFormat dateFormat = new SimpleDateFormat("MM/dd/yyyy hh:mm aa");
Date convertedDate = dateFormat.parse(datetime1);
CharSequence relavetime1 = DateUtils.getRelativeTimeSpanString(
convertedDate.getTime(),
now,
DateUtils.SECOND_IN_MILLIS,
DateUtils.FORMAT_ABBREV_RELATIVE);
And the result I get is
relativetime1=June 12, 2015
The above obtained result doesn't seem like what its supposed to look like.
By searching online I've found that if that duration is greater than a week, in which case it returns an ABSOLUTE
-I don't quite understand what I found.
How do I achieve my requirement without using an external library?
Kindly help.

Generate TimeStamp In Android Application Project

I am working on a project that requires the actions of a user to be time logged and represented as for example : 1 min ago, ...3hrs ago...5 days ago. I am new to this and don't know how to proceed. Keep in mind the project is NOT REST based. How do I implement this?
Get time in milliseconds for user action, save that time somewhere and then every time take difference of that time with current time to find out how long this action happens
you can get time in millisecond using
Calendar calendar = Calendar.getInstance();
calendar.getTimeInMillis();
You can get the actual timestamp with:
long timestamp = System.currentTimeMillis();
Regarding your question you can do something like:
long eventTimestamp = System.currentTimeMillis();
..
// some other stuff happens
..
//get the passed time
long actualTimestamp = System.currentTimeMillis();
long timestampDifference = actualTimestamp - eventTimestamp;
int passedSeconds = timestampDifference / 1000; //get the passed time in seconds
int passedMinutes= passedSeconds / 60; //get the passed time in minutes
Since you are on Android you could try the helper class DateUtils built into Android platform. Something similar to this untested code:
String relativeTime =
DateUtils.getRelativeTimeSpanString(
jud.getTime(),
System.currentTimeMillis(),
DateUtils.MINUTE_IN_MILLIS,
DateUtils.FORMAT_ABBREV_RELATIVE);
If you don't like the API-style or don't find enough features or see other problems like missing timezone awareness then you can also download and try one of two external libraries:
PrettyTime (slim classic library for relative times)
// your possible input
Date jud = new Date(System.currentTimeMillis() - 3600000);
org.ocpsoft.prettytime.PrettyTime pt =
new org.ocpsoft.prettytime.PrettyTime(Locale.ENGLISH);
String relativeTime = pt.format(jud);
System.out.println(relativeTime); // output: 1 hour ago
or my library Time4A (bigger but also more features and languages):
// your possible input
Date jud = new Date(System.currentTimeMillis() - 3600000);
Moment moment = TemporalType.JAVA_UTIL_DATE.translate(jud);
String relativeTime =
net.time4j.PrettyTime.of(Locale.US)
.withShortStyle()
.printRelativeInStdTimezone(moment);
System.out.println(relativeTime); // output: 1 hr. ago
Other libraries don't support printing of relative times well, if at all.

Android Dev: Current Time range check

I'm working on an android application, as part of me trying to learn android programming, that will switch audio profiles based on day and time (provided by the user)... So far I have got most of the layout done, I have also created a service that will run in the background to perform few checks...
Right now I'm having a hard time trying to find an elegant way to handle checking if current time falls in time range saved by the user... I'm saving the user's preference for time range in a string format from androids TimerPicker control, I need to check if the current time falls in the user saved times...
Right now I have the following code:
the 'from time' is coming in with the following: hour:minute:AM/PM -- 8:59:AM in string format
the 'to time' is coming in with the following: hour:minute:AM/PM -- 4:59:PM in string format
if(fromAMPM.equals("AM")){
from.set(from.AM_PM, from.AM);
} else {
from.set(from.AM_PM, from.PM);
}
//dont care about the YEAR and MONTH, so set it to current MONTH and YEAR
from.set(rightNow.get(rightNow.YEAR), rightNow.get(rightNow.MONTH), dayOfWeek, fromHour, fromMinute);
if(toAMPM.equals("AM")){
to.set(to.AM_PM, to.AM);
}else{
to.set(to.AM_PM, to.PM);
}
//dont care about the YEAR and MONTH, so set it to current MONTH and YEAR
to.set(rightNow.get(rightNow.YEAR), rightNow.get(rightNow.MONTH), dayOfWeek, toHour, toMinute);
//this is just for me to see what got set:
SimpleDateFormat df3 = new SimpleDateFormat("HH:mm aaa");
String formattedDate1 = df3.format(from.getTime());
String formattedDate2 = df3.format(to.getTime());
After all this processing:
formattedDate1 is returning: 08:59 AM
formattedDate2 is returning: 04:59 AM
Any suggestions?
Thanks
Take a look at the Calendar documentation, under the section "Inconsistent Information"
http://developer.android.com/reference/java/util/Calendar.html
You call:
to.set(rightNow.get(rightNow.YEAR), rightNow.get(rightNow.MONTH), dayOfWeek, toHour, toMinute);
Which sends toHour as HOUR_OF_DAY (24h), not HOUR (12h).
It says that when you supply it with inconsistent information, it just uses the latest information. You're telling it that toHour is 4 on a 24hour scale, which is inconsistent with your PM setting, so it throws the PM setting away.
The easiest change would probably be just to add 12 to toHour instead of setting the AM_PM. Or, don't use the set(year, month, day, hourofday, minute) command and just set hour and am_pm separately.

Categories

Resources