In my Android app. I am running some Task every 2 hours.How can i check that the time has exceeded 2 hours.
I tried to use this but it says depreceated
Date date = new Date();
date.setHours(date.getHours() + 2);
I would appreciate the insight on how to implement this?
Check this link
http://www.dotnetexpertsforum.com/comparing-date-time-values-in-android-t1567.html
Calendar current_time = Calendar.getInstance ();
current_time.add(Calendar.YEAR, 0);
current_time.add(Calendar.DAY_OF_YEAR, 0);
current_time.set(Calendar.HOUR_OF_DAY,
//Subtract 2 hours
current_time.get(Calendar.HOUR_OF_DAY)-2);
current_time.set(Calendar.MINUTE, 0);
current_time.set(Calendar.SECOND, 0);
Calendar given_time = Calendar.getInstance ();
given_time.set(Calendar.YEAR, syear);
//Give the day sDay and hour shour
given_time.set(Calendar.DAY_OF_YEAR, sday);
given_time.set(Calendar.HOUR_OF_DAY, shour);
given_time.set(Calendar.MINUTE, 0 );
given_time.set(Calendar.SECOND, 0);
Date current_calendar = current_time.getTime();
Date given_calendar = given_time.getTime();
System.out.println("Current Calendar "+ current_calendar);
System.out.println("Given Calendar "+ given_calendar);
boolean v = current_calendar.after(given_calendar);
if(v){
return true;
}
You should use the Calendar class.
Calendar calendar=Calendar.getInstance();
calendar.set(Calendar.HOUR_OF_DAY, calendar.get(Calendar.HOUR_OF_DAY)+2);
calendar.getTime();//your date +2 hours
use Calendar class :
Calendar cal = Calendar.getInstance();
System.out.println(cal.get(Calendar.HOUR)>(cal.get(Calendar.HOUR)+2));
Date is deprecated. Use Calendar instead.
Source: Java: Why is the Date constructor deprecated, and what do I use instead?
Two hours is 2 * 60 minutes, is 2 * 60 * 60 seconds and is 2 * 60 * 60 * 1000 milliseconds. So you can just add this number of milliseconds to your date:
Date date = new Date ();
Date after2Hours = new Date (date.getTime () + 2L * 60L * 60L * 1000L);
If you have to repeat that task every two hours, you should use Alarm manager service for that. See the link below for more details.
http://www.javacodegeeks.com/2012/09/android-alarmmanager-tutorial.html
Related
I have a java.util.Calendar variable (like 2016-05-24 00:01:05.780) and I want to get the total of seconds of the time. In this example, I want to get 65 as result.
I tried to use myCalendarVariable.getTimeInMillis()/1000 but I got -2208977011 as result.
How can I do that?
You can try
variable.get(Calendar.HOUR_OF_DAY) * 60 * 60 + variable.get(Calendar.MINUTE) * 60 + variable.get(Calendar.SECOND)
Note that Calendar.HOUR_OF_DAY is used when you're using a 24-hour clock, whereas Calendar.HOUR should be used for 12-hour clocks. In this situation you want to use the former.
Try to use get function:
myCalendarVariable.get(HOUR_OF_DAY)* 3600 + myCalendarVariable.get(MINUTE) * 60 + myCalendarVariable.get(SECOND)
Not sure which scope of seconds you were looking for, so try one of these:
Calendar myCalendarVariable = Calendar.getInstance();
int secondsInHour = myCalendarVariable.get((Calendar.MINUTE) * 60) + myCalendarVariable.get(Calendar.SECOND);
int secondsOfDay = (myCalendarVariable.get(Calendar.HOUR_OF_DAY) * 60 * 60) + secondsInHour;
You can try this:
Calendar calendar = Calendar.getInstance();
calendar.setTime(yourdate);
int minutes = calendar.get(Calendar.MINUTE);
int seconds = minutes*60 + calendar.get(Calendar.SECOND);;
If you can convert your date into a LocalDateTime you can the seconds of day directly.
The convertion from Calendar to LocalDateTime has been omitted, as you might have the data in another format. This should be easy to amend to your needs.
LocalDateTime of = LocalDateTime.of(2016, 5, 24, 0, 1, 5, 780000000);
System.out.println("seconds of day: " + of.getLong(ChronoField.SECOND_OF_DAY));
output
seconds of day: 65
I have an SQLite database that has an integer column to store a unix time stamp and I need to be able to query this column for specific days.
I am looking for a method to return the Unix time for the beginning and end of a given day. What is the best way to do this?
Here is one way to do it.
public long getStartOfDayInMillis() {
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.HOUR_OF_DAY, 0);
calendar.set(Calendar.MINUTE, 0);
calendar.set(Calendar.SECOND, 0);
calendar.set(Calendar.MILLISECOND, 0);
return calendar.getTimeInMillis();
}
public long getEndOfDayInMillis() {
// Add one day's time to the beginning of the day.
// 24 hours * 60 minutes * 60 seconds * 1000 milliseconds = 1 day
return getStartOfDayInMillis() + (24 * 60 * 60 * 1000);
}
If you want the times for a specific date, you can modify the code to handle that.
/**
* #param date the date in the format "yyyy-MM-dd"
*/
public long getStartOfDayInMillis(String date) throws ParseException {
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
Calendar calendar = Calendar.getInstance();
calendar.setTime(format.parse(date));
calendar.set(Calendar.HOUR_OF_DAY, 0);
calendar.set(Calendar.MINUTE, 0);
calendar.set(Calendar.SECOND, 0);
calendar.set(Calendar.MILLISECOND, 0);
return calendar.getTimeInMillis();
}
/**
* #param date the date in the format "yyyy-MM-dd"
*/
public long getEndOfDayInMillis(String date) throws ParseException {
// Add one day's time to the beginning of the day.
// 24 hours * 60 minutes * 60 seconds * 1000 milliseconds = 1 day
return getStartOfDayInMillis(date) + (24 * 60 * 60 * 1000);
}
I am very confused on how I can convert a given time like 9:30pm into milliseconds because I need to run a code if it is past a certain time. I already know how to get the current time in milliseconds by the following code:
long timestamp = System.currentTimeMillis();
But how would I convert 9:30pm into milliseconds? I have been researching for hours now and I can only seem to find out how to get the current time.
My application needs to check if it is 9:30pm or past and if so, run a toast message.
The fastest and correct way to do it on Android is to use Calendar. You can make Calendar instance static and reuse it whenever you need it.
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.HOUR, 9);
calendar.set(Calendar.MINUTE, 30);
calendar.set(Calendar.AM_PM, Calendar.PM);
long timeInMillis = calendar.getTimeInMillis();
I do not need to check time in milliseconds, you can compare current time with desired values using Calendar class:
Calendar calendar = Calendar.getInstance();
int hour = calendar.get(Calendar.HOUR_OF_DAY);
int minute = calendar.get(Calendar.MINUTE);
if (hour > 21 || (hour == 21 && minute >= 30)) {
doSomeJob();
}
Note that this code will not work after a midnight.
If you need time in milliseconds for 9:30pm today, you should use Calendar object to build date and time you need.
// init calendar with current date and default locale
Calendar cal = Calendar.getInstance(Locale.getDefault());
cal.setTime(new Date());
// set new time
cal.set(Calendar.HOUR_OF_DAY, 21);
cal.set(Calendar.MINUTE, 30);
cal.set(Calendar.SECOND, 0);
// obtain given time in ms
long today930PMinMills = cal.getTimeInMillis();
No need for milliseconds if you have a decent date-time library.
You can use the Joda-Time library on Android.
DateTime dateTime = new DateTime( 2014, 1, 2, 3, 4, 5 ); // Year, month, day, hour, minute, second.
boolean isNowAfterThatDateTime = DateTime.now().isAfter( dateTime );
Why don't you do it with a constant? You said that you need to check if is past 9;30. So convert that time to milliseconds and use it ad a constant. 21:30 = (21 * 60 + 30) * 60 * 1000 will give u the 9;30 in milliseconds to compare with the current time that u get in milliseconds
I have an application which use the current date and a date that is chose by user using date picker as follow:
If the date that the user chose is more than the current date +280 day,
some code will be executed.
If the date that the user chose is less than the current date , some
code will be executed.
I used this code to do so ..
Calendar start2 = Calendar.getInstance();
int birthYear = birthDayDatePicker.getYear();
int birthMonth = birthDayDatePicker.getMonth();
int birthDay = birthDayDatePicker.getDayOfMonth();
start2.set(birthYear, birthMonth, birthDay);
Calendar cal2 = Calendar.getInstance();
cal2.setTime(birthDate);
cal2.add(Calendar.DAY_OF_MONTH,daysToAdd);
birthDayChosenCalender.set(birthYear,birthMonth,birthDay);
MaxBirthDayCalender.set(currentYear, currentMonth, currentDay);
long diff = birthDayChosenCalender.getTimeInMillis() - MaxBirthDayCalender.getTimeInMillis(); //result in millis
long daysBetween = diff / (24 * 60 * 60 * 1000);
System.out.println("Days between ,,,,,,,,,,,,,,,,,,"+daysBetween);
if(MaxBirthDayCalender.before(birthDayChosenCalender) && daysBetween <= 280){
do sth }
Is there any other clean way to do that ! because this way is not working well !
The other clean way to do it is to use the Joda Time library.
Other than that, everything can be done using millis and a single calendar instance:
Calendar pickedDate = new GregorianCalendar(
picker.getYear(),
picker.getMonth(),
picker.getDayOfMonth());
long pickedTime = pickedDate.getTimeInMillis();
long now = new Date().getTime();
if (pickedTime - now <= (280 * 24 * 60 * 60 * 1000)) { // 280 days in milliseconds
// ...
}
Should cover the requirement:
I have an application which use the current date and a date that is chose by user using date picker as follow:
If the date that the user chose is more than the current date +280 day, some code will be executed.
If the date that the user chose is less than the current date , some code will be executed.
This question already has answers here:
Calculating the difference between two Java date instances
(45 answers)
Closed 9 years ago.
I want to calculate the difference between two dates.
Currently, I am doing:
Calendar firstDate = Calendar.getInstance();
firstDate.set(Calendar.DATE, 15);
firstDate.set(Calendar.MONTH, 4);
firstDate.get(Calendar.YEAR);
int diff = (new Date().getTime - firstDate.getTime)/(1000 * 60 * 60 * 24)
This gives me output 0. But I want that I should get the output 0 when the new Date() is 15. Currently the new date is 14. It makes my further calculation wrong and I am confused how to resolve this. Please suggest.
Finding the difference between two dates isn't as straightforward as
subtracting the two dates and dividing the result by (24 * 60 * 60 *
1000). Infact, its erroneous!
/* Using Calendar - THE CORRECT (& Faster) WAY**/
//assert: startDate must be before endDate
public static long daysBetween(final Calendar startDate, final Calendar endDate) {
int MILLIS_IN_DAY = 1000 * 60 * 60 * 24;
long endInstant = endDate.getTimeInMillis();
int presumedDays = (int) ((endInstant - startDate.getTimeInMillis()) / MILLIS_IN_DAY);
Calendar cursor = (Calendar) startDate.clone();
cursor.add(Calendar.DAY_OF_YEAR, presumedDays);
long instant = cursor.getTimeInMillis();
if (instant == endInstant)
return presumedDays;
final int step = instant < endInstant ? 1 : -1;
do {
cursor.add(Calendar.DAY_OF_MONTH, step);
presumedDays += step;
} while (cursor.getTimeInMillis() != endInstant);
return presumedDays;
}
You can read more on this here.
I don't think that by creating a new Date() will give you the current time and date instead do this:
Calendar cal = Calendar.getInstance();
Date currentDate = cal.getTime();
Date firstDate = new Date();
firstDate.setHour(...);
firstDate.setMinute(...);
firstDate.setSeconds(...);
long dif = currentDate.getTime() - firstDate.getTime();
So as you can see you can be as straightforward as subtracting one from another...