I want some Java code that will tell me when school is open based on the current time.
When I call this method between 9AM and 6PM it should return "school is open", otherwise it should return "school is closed" after 6 pm and before 9 am.
public Calendar shopStartTime(String msg)
{
Calendar currentTime = Calendar.getInstance();
Calendar schoolTime = Calendar.getInstance();
Calendar schoolClosedTime = Calendar.getInstance();
schoolTime.set(Calendar.HOUR_OF_DAY, 9);
schoolTime.set(Calendar.MINUTE, 0);
schoolTime.set(Calendar.SECOND, 0);
schoolTime.set(Calendar.MILLISECOND, 0);
schoolClosedTime.set(Calendar.HOUR_OF_DAY, 18);
schoolClosedTime.set(Calendar.MINUTE, 0);
schoolClosedTime.set(Calendar.SECOND, 0);
schoolClosedTime.set(Calendar.MILLISECOND, 0);
if (schoolTime.compareTo(currentTime) <= 0 &&
(currentTime.compareTo(schoolClosedTime)>=0))
{
// check for time
Toast.makeText(getSherlockActivity(), "school is closed ",
Toast.LENGTH_SHORT).show();
}
else
{
Toast.makeText(getSherlockActivity(), " school is open",
Toast.LENGTH_SHORT).show();
}
return currentTime;
}
But the code is not working because it always returns the same result. How do I test if one time is between two other time of days?
Read the javadocs!
if (currentTime.after(schoolTime) && currentTime.before(schoolClosedTime)) {
// school is open
} else {
// school is closed
}
check if hour <9 && hour >18:
(or something else)
Calendar currentTime = Calendar.getInstance();
int hour = currentTime.get(Calendar.HOUR_OF_DAY);
you only need ONE calendar
Apart from Calendar that you have used , another simple approach would be :
private boolean inRange(Date now) throws ParseException {
final Date start = new SimpleDateFormat("HH.mm.ss").parse("09.00.00");
final Date end = new SimpleDateFormat("HH.mm.ss").parse("18.00.00");
return now.after(start)&& now.before(end);
}
You can use before() and after() of Calendar as well .
Related
I have a Do Not Disturb system that mutes the sounds of my android app if the current time is in Do not disturb range time.
It works fine if I use a range time just between a day, but I dont know how to write it with one day off, For example at 11:00 pm to 1:00 am of the next day.
This is method that I used for detecting DND time:
private boolean isInDNDTime() {
Calendar now = Calendar.getInstance();
Calendar startTime = Calendar.getInstance();
Calendar endTime = Calendar.getInstance();
MyDate myDate = new MyDate(new Date());
if (isDNDTwoDays()) {
startTime.setTime(myDate.getYesterday().toDate());
startTime.set(Calendar.HOUR_OF_DAY, getDNDStartHourTime());
startTime.set(Calendar.MINUTE, getDNDStartMinuteTime());
endTime.setTime(myDate.getTomorrow().toDate());
endTime.set(Calendar.HOUR_OF_DAY, getDNDEndHourTime());
endTime.set(Calendar.MINUTE, getDNDEndMinuteTime());
} else {
startTime.set(Calendar.HOUR_OF_DAY, getDNDStartHourTime());
startTime.set(Calendar.MINUTE, getDNDStartMinuteTime());
endTime.set(Calendar.HOUR_OF_DAY, getDNDEndHourTime());
endTime.set(Calendar.MINUTE, getDNDEndMinuteTime());
}
return now.after(startTime) && now.before(endTime);
}
Pls try below code
private boolean isInDNDTime() {
Calendar now = Calendar.getInstance();
Calendar startTime = Calendar.getInstance();
Calendar endTime = Calendar.getInstance();
MyDate myDate = new MyDate(new Date());
if (isDNDTwoDays()) {
startTime.add(Calendar.DATE, 1);
endTime.add(Calendar.DATE, 1);
// startTime.setTime(myDate.getYesterday().toDate());
startTime.set(Calendar.HOUR_OF_DAY, getDNDStartHourTime());
startTime.set(Calendar.MINUTE, getDNDStartMinuteTime());
// endTime.setTime(myDate.getTomorrow().toDate());
endTime.set(Calendar.HOUR_OF_DAY, getDNDEndHourTime());
endTime.set(Calendar.MINUTE, getDNDEndMinuteTime());
} else {
startTime.set(Calendar.HOUR_OF_DAY, getDNDStartHourTime());
startTime.set(Calendar.MINUTE, getDNDStartMinuteTime());
endTime.set(Calendar.HOUR_OF_DAY, getDNDEndHourTime());
endTime.set(Calendar.MINUTE, getDNDEndMinuteTime());
}
return now.after(startTime) && now.before(endTime);
}
There is a modern API for tasks like this, it is called java.time and is available from Java 8. The following example illustrates how to do that with a few lines of code:
public static void main(String[] args) {
// create sample data
LocalDateTime start = LocalDateTime.of(2020, 2, 19, 12, 30);
LocalDateTime timeInDND = LocalDateTime.now();
LocalDateTime end = LocalDateTime.of(2020, 2, 21, 12, 30);
// just check if the time is equal to start or end or is between them
if (timeInDND.equals(start) || timeInDND.equals(end)
|| (timeInDND.isAfter(start) && timeInDND.isBefore(end))) {
System.out.println(timeInDND.format(DateTimeFormatter.ISO_LOCAL_DATE_TIME)
+ " is in the DND period");
} else {
System.err.println(timeInDND.format(DateTimeFormatter.ISO_LOCAL_DATE_TIME)
+ " is not in the DND period");
}
}
Unfortunately, your support of Android API levels below 26 requires an external library, the ThreeTen Android Backport because java.time is available from API level 26. You can check another question about how to use the ThreeTenABP.
This question already has answers here:
Get the week start and end date given a current date and week start
(4 answers)
Closed 8 years ago.
I have the date and time stored in preferences as Long:
// put
SharedPreferences settings =
PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
settings.edit().putLong("pref_datetime", System.currentTimeMillis()).commit();
// get
Date date2 = new Date(settings.getLong("pref_datetime", 0));
Once date is extracted, how could I check if it belongs to the current week (starting on Monday) or not?
You can use a Calendar instance to create this Monday and next Monday Date instances based on the current date then check that your date lies between them.
Calendar c = Calendar.getInstance();
c.setFirstDayOfWeek(Calendar.MONDAY);
c.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY);
c.set(Calendar.HOUR_OF_DAY, 0);
c.set(Calendar.MINUTE, 0);
c.set(Calendar.SECOND, 0);
c.set(Calendar.MILLISECOND, 0);
Date monday = c.getTime();
Date nextMonday= new Date(monday.getTime()+7*24*60*60*1000);
boolean isThisWeek = date2.after(monday) && date2.before(nextMonday);
You can construct a Calendar, and use getField(int) to get both the Calendar.YEAR and the Calendar.WEEK_OF_YEAR. When those are the same, the two Dates are from the same week.
When constructing the Calendar, also call setFirstDayOfWeek(Calendar.MONDAY) to make sure the weeks start on Monday (if you don't, it depends on the current locale).
After #SiKelly's objection that this won't work reliably in the end of December, beginning of January:
Compare WEEK_OF_YEAR.
If not equal, it is a different week.
If equal, it could be the wrong year, but that is hard to check. So just also check that the difference in getTime() is less than 8 * 24 * 60 * 60 * 1000 (eight days to be on the safe side).
(you could do step 3 first. then you avoid having to construct the calendar at all in many cases).
You can use Calendar to calculate week number for today and your date also,then simpy try to match it,
// put
SharedPreferences settings =
PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
settings.edit().putLong("pref_datetime", System.currentTimeMillis()).commit();
// get
Date date2 = new Date(settings.getLong("pref_datetime", 0));
Calendar calendar = Calendar.getInstance();
calendar.setFirstDayOfWeek(Calendar.MONDAY);
int current_year = calendar.get(Calendar.YEAR);
int current_week_number = calendar.get(Calendar.WEEK_OF_YEAR);
calendar.setTime(date2);
int year = calendar.get(Calendar.YEAR);
int week_number= calendar.get(Calendar.WEEK_OF_YEAR);
if(current_year==year && current_week_number==week_number)
{
//same
}
else
{
//different
}
try this
private boolean is_ThisWeek(Date date2){
Date now =new Date(System.currentTimeMillis());
int diffInDays = (int)( (now.getTime() - date2.getTime())
/ (1000 * 60 * 60 * 24) );
Calendar calendar = Calendar.getInstance();
calendar.setTime(now);
int reslut = calendar.get(Calendar.DAY_OF_WEEK);
int days_before = get_days_before(reslut);
if (diffInDays<days_before) {
Toast.makeText(this, "this week", Toast.LENGTH_SHORT).show();
return true;
}else {
Toast.makeText(this,"not this week", Toast.LENGTH_SHORT).show();
return false;
}
}
int get_days_before(int reslut){
int days_before = 0;
switch (reslut) {
case Calendar.MONDAY:
days_before=1;
break;
case Calendar.TUESDAY:
days_before=2;
break;
case Calendar.WEDNESDAY:
days_before=3;
break;
case Calendar.THURSDAY:
days_before=4;
break;
case Calendar.FRIDAY:
days_before=5;
break;
case Calendar.SATURDAY:
days_before=6;
break;
case Calendar.SUNDAY:
days_before=7;
break;
}
return days_before;
}
i have a table in oracle where I saved the twelve public days in Mexico and I need to calculate a limit day since you registered
public Date calcularFechaLimite() {
try {
DiaFestivoDTO dia = new DiaFestivoDTO();
// Calendar fechaActual = Calendar.getInstance();
Calendar fechaL = Calendar.getInstance();
fechaL.add(Calendar.DATE, 3);
switch (fechaL.get(Calendar.DAY_OF_WEEK)) {
case Calendar.SATURDAY:
fechaL.add(Calendar.DATE, 2);
break;
case Calendar.SUNDAY:
fechaL.add(Calendar.DATE, 2);
break;
case Calendar.MONDAY:
fechaL.add(Calendar.DATE, 2);
break;
case Calendar.TUESDAY:
fechaL.add(Calendar.DATE, 1);
default:
break;
}
dia.setFechaLimite(fechaL.getTime());
Integer numeroDiasFest = seleccionPagoBO.obtenerDiasFestivos(dia);
if (numeroDiasFest != 0) {
fechaL.add(Calendar.DATE, numeroDiasFest);
dia.setFechaLimite(fechaL.getTime());
}
fechaLimite = fechaL.getTime();
} catch (Exception e) {
e.printStackTrace();
}
return fechaLimite;
}
This is what i have but March 28 and 29 are public days and it is not working, any idea??
Several issues:
You are not checking if the first 3 days you skip contain weekend days.
Also you are skipping strange amounts of days and skipping for weekdays as well (which are business days and therefore should not be skipped).
I assume the method DiaFestivoDTO.obtenerDiasFestivos() calculates the number of national holidays in a certain date range but what is the start date? Is it initialized to the current date when DiaFestivoDTO is created?
When there is a national holiday in your date range you increase the date range but never check if this new daterange includes new national holidays or weekend days.
If what you are trying to do is calculate a date '3 business days from now' here's roughly what I would do:
// get all the holidays as java.util.Date
DiaFestivoDTO dia = new DiaFestivoDTO();
List<Date> holidays = dia.getAllNationalHolidays();
// get the current date without the hours, minutes, seconds and millis
Calendar cal = Calendar.getInstance();
cal.set(Calendar.HOUR_OF_DAY, 0);
cal.set(Calendar.MINUTE, 0);
cal.set(Calendar.SECOND, 0);
cal.set(Calendar.MILLISECOND, 0);
// iterate over the dates from now and check if each day is a business day
int businessDayCounter = 0
while (businessDayCounter < 3) {
int dayOfWeek = cal.get(Calendar.DAY_OF_WEEK);
if (dayOfWeek != Calendar.SATURDAY && dayOfWeek != Calendar.SUNDAY && !holidays.contains(cal.getTime())) {
businessDayCounter++;
}
cal.add(Calendar.DAY_OF_YEAR, 1);
}
Date threeBusinessDaysFromNow = cal.getTime();
For this to work I would advise you to add a new method 'getAllNationalHolidays' to list al the holidays because it is more efficient to store twelve dates in memory than to access the database multiple times to check for them.
If you cannot change/add database methods then you could do this
while (businessDayCounter < 3) {
// determine if this day is a holiday
DiaFestivoDTO dia = new DiaFestivoDTO();
dia.setFechaInitial(cal.getTime());
dia.setFechaLimite(cal.getTime());
boolean isHoliday = seleccionPagoBO.obtenerDiasFestivos(dia) > 0;
int dayOfWeek = cal.get(Calendar.DAY_OF_WEEK);
if (dayOfWeek != Calendar.SATURDAY && dayOfWeek != Calendar.SUNDAY && !isHoliday) {
businessDayCounter++;
}
cal.add(Calendar.DAY_OF_YEAR, 1);
}
Here I assumed you can set the 'from' date in your DiaFestivoDTO using 'setFechaInitial' or something like that. But in this way you would be calling the database at least three times which is inefficient.
I would like to get the current time on the android device with the app installed.
I want to be able to do something like this..
if(//time is pass noon){
//Do something
}
else{
//do something.
}
i want to tell if its am or pm.
Here is an example that should help you:
Calendar today = Calendar.getInstance();
Calendar expireDate = Calendar.getInstance();
expireDate.set(2011, Calendar.AUGUST, 12);
if (today.compareTo(expireDate) == 0 || today.compareTo(expireDate) == 1)
{
// expired - please purchase app
}
else
{
// do some stuff
}
To tell if it is AM or PM use:
int value = today.get(Calendar.AM_PM);
Or you could just get the hour:
int hour = today.get(Calendar.HOUR);
And then put that in an if statement:
if (hour > 12)
{
// do stuff
}
else
{
// do other stuff
}
You will get time here in 24 hrs format.So you can do as you like
final Calendar cld = Calendar.getInstance();
int time = cld.get(Calendar.HOUR_OF_DAY);
if(time>12){
//noon
}else{
//
}
Calendar now = Calendar.getInstance();
if (now.get(Calendar.AM_PM) == Calendar.AM) {
System.out.println("AM: Before noon");
} else { // == Calendar.PM
System.out.println("PM: After noon");
}
The current time is available with
new Date()
Parsing that for the time you can figure out if is AM or PM local time for the device.
This question already has answers here:
Closed 11 years ago.
Possible Duplicates:
How do I compare a raw time in Java to now?
How do I compare a raw time in Java?
It doesnt matter which day.
I have to know if currently it is after 10AM or before.
You can use:
Date yourDate = new Date();
GregorianCalendar calendar = new GregorianCalendar();
calendar.setTime(yourDate);
boolean before10AM = calendar.get(Calendar.HOUR_OF_DAY) < 10;
Check out the documentation for Calendar to find out more of the stuff you can do with it (such as, for example, you can find out if your date is a friday or not).
In previous versions of the JDK, you could use Date.getHours(), but that is now deprecated in favor of the Calendar class.
Here you go:
Date date = new Date();
int hours = date.getHours();
if ( hours < 10) {
System.out.println("before 10 am");
} else {
System.out.println("after 10 am");
}
// if deprecated methods are an issue then
Calendar cal = Calendar.getInstance();
cal.setTime(date);
int calHours = cal.get(Calendar.HOUR_OF_DAY);
if ( calHours < 10) {
System.out.println("before 10 am");
} else {
System.out.println("after 10 am");
}
The whole thing can be done a lot more cleanly using the joda-time library.
Calendar calendar = new GregorianCalendar();
calendar.setTime(yourDate);
Calendar calendar1 = new GregorianCalendar();
calendar1.set(Calendar.YEAR, calendar.get(Calendar.YEAR));
calendar1.set(Calendar.MONTH, calendar.get(Calendar.MONTH));
calendar1.set(Calendar.DATE, calendar.get(Calendar.DATE));
calendar1.set(Calendar.HOUR_OF_DAY, YOUR_HOUR);
calendar1.set(Calendar.MINUTE, YOUR_MINUTE);
calendar1.set(Calendar.SECOND, 0);
calendar1.set(Calendar.MILLISECOND, 0);
Date date = calendar1.getTime();
if (yourDate.after(date)) {
System.out.println("After");
}