How to calculate a time between two times with one day off? - java

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.

Related

Check my current time is exist between 7:00 PM -10.00 AM in java android

Example: my current time = 8:25 PM it means the current time is inside 7:00 PM to 10.00 AM. So how can I determined it & if inside show a message?
It's for a restaurant time restriction. from 7:00 PM to 10.00 AM time range user can't order anything.
try {
// Start Time
String string1 = "07:00 PM";
Date time1 = new SimpleDateFormat("hh:mm a").parse(string1);
Calendar calendar1 = Calendar.getInstance();
calendar1.setTime(time1);
calendar1.add(Calendar.DATE, 1);
// End Time
String string2 = "10:00 AM";
Date time2 = new SimpleDateFormat("hh:mm a").parse(string2);
Calendar calendar2 = Calendar.getInstance();
calendar2.setTime(time2);
calendar2.add(Calendar.DATE, 1);
// Get Current Time
Date date = new Date();
SimpleDateFormat sdf = new SimpleDateFormat("hh:mm a");
String currenttime = sdf.format(date);
Date d = new SimpleDateFormat("hh:mm a").parse(currenttime);
Calendar calendar3 = Calendar.getInstance();
calendar3.setTime(d);
calendar3.add(Calendar.DATE, 1);
Date x = calendar3.getTime();
if (x.after(calendar1.getTime()) && x.before(calendar2.getTime())) {
System.out.println("Not possible to order now");
}
else
{
System.out.println("YES POSSIBLE");
}
} catch (ParseException e) {
e.printStackTrace();
}
Here if you want to avoid NullPointerException & ParseException checking:
public static boolean isAvailableForBooking() {
/* 10:00 AM */
final int OPEN_HOUR = 10; /* 0 - 23*/
final int OPEN_MINUTE = 0; /* 0 - 59*/
final int OPEN_SECOND = 0; /* 0 - 59*/
/* 07:00 PM */
final int CLOSED_HOUR = 19;
final int CLOSED_MINUTE = 0;
final int CLOSED_SECOND = 0;
Calendar openHour = Calendar.getInstance();
openHour.set(Calendar.HOUR_OF_DAY, OPEN_HOUR);
openHour.set(Calendar.MINUTE, OPEN_MINUTE);
openHour.set(Calendar.SECOND, OPEN_SECOND);
Calendar closedHour = Calendar.getInstance();
closedHour.set(Calendar.HOUR_OF_DAY, CLOSED_HOUR);
closedHour.set(Calendar.MINUTE, CLOSED_MINUTE);
closedHour.set(Calendar.SECOND, CLOSED_SECOND);
Calendar now = Calendar.getInstance();
return now.after(openHour) && now.before(closedHour);
}
tl;dr
Use modern java.time class, LocalTime.
( ! localTime.isBefore( LocalTime.of( 19 , 0 ) ) ) // Is not before the start… (meaning, is equal to or later than)
&& // …and…
localTime.isBefore( LocalTime.of( 7 , 0 ) ) ; // is before the end.
java.time
Never use Calendar or Date classes. These terrible classes were supplanted years ago by the modern java.time classes defined in JSR 310.
LocalTime start = LocalTime.of( 19 , 0 ) ; // 7 PM.
LocalTime end = LocalTime.of( 10 , 0 ) ; // 10 AM.
Determining the current time requires a time zone. For any given moment, the time of day, and the date, varies around the globe by zone.
If you want to use the JVM’s current default time zone, call ZoneId.systemDefault().
ZoneId z = ZoneId.of( "Africa/Casablanca" ) ;
LocalTime localTime = LocalTime.now( z ) ;
Ask if the current time is equal to or later than the start and before the end. Tip: another way to ask “is equal to or later” is “is not before”.
boolean withinTimeRange = ( ! localTime.isBefore( start ) ) && localTime.isBefore( end ) ;
For early Android before 26, add the ThreeTenABP library to your project to get most of the java.time functionality with nearly the same API.
If you tried any code then please post it otherwise, You can check it by setting your current time and your service start time and end time on a Calendar Object and then get Date object from the calendar and can compare these dates.
String SERVICE_START_TIME="202-05-04 19:00:00";
String SERVICE_END_TIME="202-05-05 10:00:00";
public static boolean isValidTime() {
try {
Date time1 = new SimpleDateFormat("yyyy-mm-dd HH:mm:ss",
Locale.getDefault()).parse(SERVICE_START_TIME);
Calendar calendar1 = Calendar.getInstance();
calendar1.setTime(time1);
calendar1.add(Calendar.DATE, 1);
Date time2 = new SimpleDateFormat("yyyy-mm-dd HH:mm:ss",
Locale.getDefault()).parse(SERVICE_END_TIME);
Calendar calendar2 = Calendar.getInstance();
calendar2.setTime(time2);
calendar2.add(Calendar.DATE, 1);
Date d = new SimpleDateFormat("yyyy-mm-dd HH:mm:ss",
Locale.getDefault()).parse(getCurrentTime());
Calendar calendar3 = Calendar.getInstance();
calendar3.setTime(d);
calendar3.add(Calendar.DATE, 1);
Date now = calendar3.getTime();
if (now.after(calendar1.getTime()) && now.before(calendar2.getTime())) {
return true;
}
} catch (ParseException e) {
e.printStackTrace();
}
return false;
}
You can get your system current time by using this function.
private static String getCurrentTime() {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-mm-dd HH:mm:ss",
Locale.getDefault());
return sdf.format(new Date()).toUpperCase();
}
Simpler solution would be to take time bounds in milliseconds. Then take your desired time in milliseconds and do the check lowerBound < desiredTime < upperBound.

List all weeks,months and year in JAVA/Android

Is it possible to list the all weeks/date given two date range for example:
Date from 1/1/2013 to 1/1/2020
result will be:
1-7,2013
8-14,2013
15-21,2013 and soon til 2020 and same with month.
Please try out this for the case of weeks(check if you can optimize).
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// to provide month range dynamically
Calendar calendar = Calendar.getInstance();
Date minDate = calendar.getTime();
calendar.add(Calendar.MONTH, 5); // current month + 5 months calendar
Date maxDate = calendar.getTime();
SimpleDateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy");
String startDate = dateFormat.format(minDate);
String endDate = dateFormat.format(maxDate);
List<Date> dates = getDates(startDate, endDate); // to get dates between range
int prevIdentifier = 0;
int identifier;
String initDate, finalDate;
List<WeekDay> weekDays = getListOfWeeksFromListOfDates(dates);
SimpleDateFormat dformatter = new SimpleDateFormat("dd");
SimpleDateFormat yformatter = new SimpleDateFormat("yyyy");
initDate = dformatter.format(weekDays.get(0).getDate());
finalDate = dformatter.format(weekDays.get(0).getDate());
String outputData = "";
for (WeekDay weekDay : weekDays) {
identifier = Integer.parseInt(weekDay.getWeekIdentifier()); // this value will be same for all days in same week
if (prevIdentifier != 0 && identifier != prevIdentifier) {
if (outputData.equalsIgnoreCase(""))
outputData += initDate + "-" + finalDate + "," + yformatter.format(weekDay.getDate());
else
outputData += " * " + initDate + "-" + finalDate + "," + yformatter.format(weekDay.getDate());
initDate = dformatter.format(weekDay.getDate());
} else {
finalDate = dformatter.format(weekDay.getDate());
}
prevIdentifier = identifier;
}
System.out.println("OUTPUT DATA :" + outputData);
}
public List<WeekDay> getListOfWeeksFromListOfDates(List<Date> listOfDates) {
List<WeekDay> listOfWeeks = new ArrayList<>();
WeekDay weekDay;
for (Date date : listOfDates) {
weekDay = new WeekDay(date, new SimpleDateFormat("w").format(date));
listOfWeeks.add(weekDay);
}
return listOfWeeks;
}
public class WeekDay {
Date date;
String weekIdentifier;
public WeekDay(Date Date, String WeekIdentifier) {
this.date = Date;
this.weekIdentifier = WeekIdentifier;
}
public Date getDate() {
return date;
}
public String getWeekIdentifier() {
return weekIdentifier;
}
}
private static List<Date> getDates(String dateString1, String dateString2) {
ArrayList<Date> dates = new ArrayList<Date>();
DateFormat df1 = new SimpleDateFormat("dd/MM/yyyy");
Date date1 = null;
Date date2 = null;
try {
date1 = df1.parse(dateString1);
date2 = df1.parse(dateString2);
} catch (ParseException e) {
e.printStackTrace();
}
Calendar cal1 = Calendar.getInstance();
cal1.setTime(date1);
Calendar cal2 = Calendar.getInstance();
cal2.setTime(date2);
while (!cal1.after(cal2)) {
dates.add(cal1.getTime());
cal1.add(Calendar.DATE, 1);
}
return dates;
}
java.time
I would use a LocalDate for start date (e.g., 1/1/2013) and one for end date (1/1/2020). To represent the period you want (week, month or year) I might use either the appropriate ChronoUnit constant or — more flexibly — a Period. The mentioned classes are from java.time, the modern Java date and time API. A pretty simple loop will iterate through your start dates (Jan 1, Jan 8, Jan 15, etc.). Subtract 1 from each start date (except the first) to get the end dates (Jan 8 minus 1 day gives Jan 7, etc.).
Question: Can I use java.time on Android?
Yes, java.time works nicely on Android devices. It just requires at least Java 6.
In Java 8 and later and on new Android devices (from API level 26, I’m told) the new API comes built-in.
In Java 6 and 7 get the ThreeTen Backport, the backport of the new classes (ThreeTen for JSR 310, where the modern API was first described).
On (older) Android, use the Android edition of ThreeTen Backport. It’s called ThreeTenABP. Make sure you import the date and time classes from package org.threeten.bp and subpackages.
Links
Oracle tutorial: Date Time, explaining how to use java.time.
Documentation of LocalDate, ChronoUnit and Period.
ThreeTen Backport project
ThreeTenABP, Android edition of ThreeTen Backport
Question: How to use ThreeTenABP in Android Project, with a very thorough explanation.
Java Specification Request (JSR) 310.

Checking time interval in java

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 .

How can I manage working hours in Java?

I want to ask if someone knows any API or something similar that allows me to manage concrete parts of day (for example working hours)
My problem is that I have to manage times in the next context:
imagine I am working in a company which working hours is "8am-2pm" and "3pm-6pm" and with a daylight saving time from "8am to 2pm". I want to know if a concrete moment of a concrete date is a laboral moment or if it isn't.
For example if I have the mentioned calendar, and I ask the API if the "13th august 2012 at 9pm" is a working moment it has to check it and return a correct answer (false in this case) and if I ask if the "13th august 2012 at 9am" is a working moment it has to return "true"
Other important thing related. I have to calculate intervals between two dates with the mentioned calendar. For example, if i set begin time as "today at 5pm" and end time "tomorrow at 10am" it has to return 3 hours (or its equivalent in seconds or milliseconds) because it is the correct time period passed between the begin date and the end date in this calendar.
It also has to work with holidays (particular of each country). I found an API call "JollyTime" but, although it works with holidays, it does not support the working hours...
Any idea?
Update: The Joda-Time library is now in maintenance-mode, its principal author Stephen Colebourne having gone on to lead JSR 310 that defines the java.time classes built into Java 8 and later.
A good database with sophisticated support for date-times may be of assistance here. One such database is Postgres, with good date-time data types and commands ("functions").
The Joda-Time framework may help as well. The Interval class and its parent classes define a span of time between a pair of start & stop date-times. They offer methods for comparison such as: contains, overlaps, isBefore, is After.
Here's some example code to get you started, using Joda-Time 2.3 with Java 7.
// © 2013 Basil Bourque. This source code may be used freely forever by anyone taking full responsibility for doing so.
// import org.joda.time.*;
// import org.joda.time.format.*;
DateTimeZone timeZone = DateTimeZone.forID( "Europe/Paris" );
List<Interval> workIntervalsFor13Aug2012 = new ArrayList<Interval>( 2 );
DateTime start, stop;
Interval interval;
start = new DateTime( 2012, 8, 13, 8, 0, 0, timeZone );
stop = new DateTime( 2012, 8, 13, 14, 0, 0, timeZone );
interval = new org.joda.time.Interval( start, stop );
workIntervalsFor13Aug2012.add( interval );
start = new DateTime( 2012, 8, 13, 15, 0, 0, timeZone );
stop = new DateTime( 2012, 8, 13, 18, 0, 0, timeZone );
interval = new org.joda.time.Interval( start, stop );
workIntervalsFor13Aug2012.add( interval );
// Check a date-time against those work intervals.
DateTime test09 = new DateTime( 2012, 8, 13, 9, 0, 0, timeZone );
DateTime test21 = new DateTime( 2012, 8, 13, 21, 0, 0, timeZone );
// You should write a "dateTimeIsInWorkingInterval" method that performs this loop.
Boolean hit = false;
for ( Interval nthInterval : workIntervalsFor13Aug2012 ) {
if( nthInterval.contains( test09 )) {
hit = true;
break;
}
}
if( hit ) {
System.out.println( "This date-time: " + test09 + " occurs during a work interval.");
} else {
System.out.println( "This date-time: " + test09 + " occurs outside a work interval.");
}
hit = false;
for ( Interval nthInterval : workIntervalsFor13Aug2012 ) {
if( nthInterval.contains( test21 )) {
hit = true;
break;
}
}
if( hit ) {
System.out.println( "This date-time: " + test21 + " occurs during a work interval.");
} else {
System.out.println( "This date-time: " + test21 + " occurs outside a work interval.");
}
When run…
This date-time: 2012-08-13T09:00:00.000+02:00 occurs during a work interval.
This date-time: 2012-08-13T21:00:00.000+02:00 occurs outside a work interval.
Take a look at the JODA Time library. I know it has intervals and might be just what you need.
I have implemented a simple solution to calculate working hours between two dates. Starting from this point of view may help you achieve your task.
Here is the class that calculates working time as minutes or miliseconds.
public class WorkingTime {
private static final long ONE_SECOND_AS_MILISECONDS = TimeUnit.SECONDS.convert(1, TimeUnit.SECONDS);
private Integer startHour;
private Integer endHour;
private Integer startMinute;
private Integer endMinute;
public WorkingTime(int startHour, int endHour) {
this(startHour, 0, endHour, 0);
}
public WorkingTime(Integer startHour, Integer startMinute,
Integer endHour, Integer endMinute) {
super();
this.startHour = startHour;
this.endHour = endHour;
this.startMinute = startMinute;
this.endMinute = endMinute;
}
... getters and setters
public long calculateWorkingAsMilis(Date date1, Date date2) {
return ONE_SECOND_AS_MILISECONDS * calculateWorkingSeconds(date1, date2);
}
public long calculateWorkingSeconds(Date date1, Date date2) {
Calendar cal1 = Calendar.getInstance();
cal1.setTime(date1);
setWorkingCalendar(cal1);
Calendar cal2 = Calendar.getInstance();
cal2.setTime(date2);
setWorkingCalendar(cal2);
long day1 = TimeUnit.MILLISECONDS.toDays(cal1.getTimeInMillis());
long day2 = TimeUnit.MILLISECONDS.toDays(cal2.getTimeInMillis());
long daydiff = day2 - day1;
long weekendDiff = (daydiff / 7); // get number of weekends
if (isLeakWeekend(cal1, cal2))
weekendDiff++;
long dailyWorkingTimeAsMinutes = getDailyWorkingTimeAsMinutes();
long secondsToBeDecrementedAsNonWorkingHours = TimeUnit.SECONDS.convert((24 * 60 - dailyWorkingTimeAsMinutes), TimeUnit.MINUTES); // seconds that are not in interval of working hours
long secondsToBeDecrementedAsWorkingHoursForWeekends = TimeUnit.SECONDS.convert(dailyWorkingTimeAsMinutes * 2, TimeUnit.MINUTES); // weekend is not working days, they need to be decremented
long dayDiffAsSeconds = daydiff * secondsToBeDecrementedAsNonWorkingHours;
dayDiffAsSeconds += (weekendDiff * secondsToBeDecrementedAsWorkingHoursForWeekends);
long workDiffSeconds = TimeUnit.SECONDS.convert(
cal2.getTimeInMillis() - cal1.getTimeInMillis(),
TimeUnit.MILLISECONDS) - dayDiffAsSeconds;
return workDiffSeconds;
}
private boolean isLeakWeekend(Calendar cal1, Calendar cal2) {
if (cal1.get(Calendar.DAY_OF_WEEK) > cal2.get(Calendar.DAY_OF_WEEK))
return true;
return false;
}
private long getDailyWorkingTimeAsMinutes() {
return (getEndHour() * 60 + getEndMinute()) - (getStartHour() * 60 + getStartMinute());
}
private Calendar setWorkingCalendar(Calendar cal) {
if (cal.get(Calendar.DAY_OF_WEEK) == Calendar.SUNDAY) {
cal.set(Calendar.DAY_OF_YEAR, cal.get(Calendar.DAY_OF_YEAR) + 1);
resetWorkingHourAndSeconds(cal);
} else if (cal.get(Calendar.DAY_OF_WEEK) == Calendar.SATURDAY) {
cal.set(Calendar.DAY_OF_YEAR, cal.get(Calendar.DAY_OF_YEAR) + 2);
resetWorkingHourAndSeconds(cal);
} else if (cal.get(Calendar.HOUR_OF_DAY) > endHour || (cal.get(Calendar.HOUR_OF_DAY) == endHour && cal.get(Calendar.MINUTE) > endMinute)) {
cal.set(Calendar.HOUR_OF_DAY, endHour);
cal.set(Calendar.MINUTE, endMinute);
} else if (cal.get(Calendar.HOUR_OF_DAY) < startHour || (cal.get(Calendar.HOUR_OF_DAY) == startHour && cal.get(Calendar.MINUTE) < startMinute)) {
cal.set(Calendar.HOUR_OF_DAY, startHour);
cal.set(Calendar.MINUTE, startMinute);
}
return cal;
}
private Calendar resetWorkingHourAndSeconds(Calendar cal) {
cal.set(Calendar.HOUR_OF_DAY, startHour);
cal.set(Calendar.MINUTE, startMinute);
cal.set(Calendar.SECOND, 0);
cal.set(Calendar.MILLISECOND, 0);
return cal;
}
}
And here is the usage
// create an instance (working hours from 08:30 to 17:30)
WorkingTime workingTime = new WorkingTime(8, 30, 17, 30);
long durationAsMilis = workingTime.calculateWorkingAsMilis(date1, date2);
Hope that helps
Tuncay Senturk

java - I have a Date(). How do I know if it is after HH:MM or not? [duplicate]

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");
}

Categories