Knowing if time has passed in java - java

I would like to know if the current time has passed 12 pm already. Can I do it in an if statement like:
if(timenow is already pass 12 pm){
**do code here**
}
Is there a java code or a method in joda time that can do that? All answers are appreciated. Thanks. :)

Calendar cal = Calendar.getInstance();
if (cal.get(Calendar.HOUR_OF_DAY) >= 12) {
...
}

JAVA
int hour = LocalDateTime.now().getHour();
JODATIME
DateTime dt = new DateTime(); // current time
int hour = dt.getHourOfDay(); // gets hour of day
and put the logic here
if(hour >= 12){
do code here
}

Related

My method that returns the number of working days in the current month is returning one day less

I have the following method that I took from the accepted answer this question Calculate number of weekdays between two dates in Java
public static int getWorkingDaysBetweenTwoDates(Date startDate, Date endDate) {
Calendar startCal = Calendar.getInstance();
startCal.setTime(startDate);
Calendar endCal = Calendar.getInstance();
endCal.setTime(endDate);
int workDays = 0;
//Return 0 if start and end are the same
if (startCal.getTimeInMillis() == endCal.getTimeInMillis()) {
return 0;
}
if (startCal.getTimeInMillis() > endCal.getTimeInMillis()) {
startCal.setTime(endDate);
endCal.setTime(startDate);
}
do {
//excluding start date
startCal.add(Calendar.DAY_OF_MONTH, 1);
if (startCal.get(Calendar.DAY_OF_WEEK) != Calendar.SATURDAY && startCal.get(Calendar.DAY_OF_WEEK) != Calendar.SUNDAY) {
++workDays;
}
} while (startCal.getTimeInMillis() < endCal.getTimeInMillis()); //excluding end date
return workDays;
}
I pass to that function the first day and the last day of the current month I get the days like this:
Calendar firstDayOfMonth = Calendar.getInstance();
firstDayOfMonth .set(Calendar.DAY_OF_MONTH,
Calendar.getInstance().getActualMinimum(Calendar.DAY_OF_MONTH));
Calendar lastDayOfMonth = Calendar.getInstance();
lastDayOfMonth .set(Calendar.DAY_OF_MONTH,
Calendar.getInstance().getActualMaximum(Calendar.DAY_OF_MONTH));
and I pass the parameters to the function like this:
getWorkingDaysBetweenTwoDates(firstDayOfMonth.getTime(),
lastDayOfMonth.getTime());
I try the method and is returning 21 and we are in November of 2016 and this month have 22 working days not 21
I printed in console the parameters and these are the paramaters that I'm passing to the method
firstDayOfMonth.getTime() //equals to this Tue Nov 01 09:09:47 VET 2016
lastDayOfMonth.getTime() //equals to this Wed Nov 30 09:09:47 VET 2016
Indeed, to have the correct number :
do {
// excluding start date
startCal.add(Calendar.DAY_OF_MONTH, 1);
if (startCal.get(Calendar.DAY_OF_WEEK) != Calendar.SATURDAY && startCal.get(Calendar.DAY_OF_WEEK) != Calendar.SUNDAY) {
++workDays;
}
}
should be replaced by :
do {
// excluding start date
if (startCal.get(Calendar.DAY_OF_WEEK) != Calendar.SATURDAY && startCal.get(Calendar.DAY_OF_WEEK) != Calendar.SUNDAY) {
++workDays;
}
startCal.add(Calendar.DAY_OF_MONTH, 1);
}
But I see another problem.
To give a correct result, the function supposes that there is a little time difference between the two date parameters :
For example, if you provide two dates (01-11-2016 and 30-11-2016) with last part of the datetime to 00:00:00:00, the days number returned will be 21.
If you create one date, after the second date, you will get 22.
The problem happens here :
while (startCal.getTimeInMillis() < endCal.getTimeInMillis());
Because even if it has only some milliseconds between startCal and endCal in the last iteration, it adds one undesirable day in the result.
To have a deterministic result, you should consider only day (and not time) in the transmitted dates :
Calendar firstDayOfMonth = Calendar.getInstance();
firstDayOfMonth.set(Calendar.MILLISECOND, 0);
firstDayOfMonth.set(Calendar.SECOND, 0);
firstDayOfMonth.set(Calendar.MINUTE, 0);
firstDayOfMonth.set(Calendar.HOUR, 0);
firstDayOfMonth.set(Calendar.DAY_OF_MONTH,
Calendar.getInstance().getActualMinimum(Calendar.DAY_OF_MONTH));
Calendar lastDayOfMonth = Calendar.getInstance();
lastDayOfMonth.set(Calendar.MILLISECOND, 0);
lastDayOfMonth.set(Calendar.SECOND, 0);
lastDayOfMonth.set(Calendar.MINUTE, 0);
lastDayOfMonth.set(Calendar.HOUR, 0);
lastDayOfMonth.set(Calendar.DAY_OF_MONTH,
Calendar.getInstance().getActualMaximum(Calendar.DAY_OF_MONTH));
int nbDays = getWorkingDaysBetweenTwoDates(firstDayOfMonth.getTime(),
lastDayOfMonth.getTime());
and use this condition in the loop :
while (startCal.getTimeInMillis() <= endCal.getTimeInMillis());
This condition seems more natural since if the actual date is not after the last date (so before or equals), it should increment the counter for one additional day. Why exclude the last day ?
With Java 8 or JodaTime, it would be more simple and clean to set date values.
To avoid this kind of problem, I think that the getWorkingDaysBetweenTwoDates() method should reset to zero the time part of date parameters or use more specificDate objects (LocalDate for example) as parameters.
Replace startCal.getTimeInMillis() < endCal.getTimeInMillis()) with startCal.getTimeInMillis() <= endCal.getTimeInMillis()).
You current code act like end date not included in range.

How do I figure out whether the current time is in between two times? [duplicate]

This question already has answers here:
How can I determine if a date is between two dates in Java? [duplicate]
(11 answers)
Closed 9 years ago.
I'm trying to write a schedule program in Java and I need to figure out what time it is, and whether the current time is in between two set times. Figuring out the current time is pretty simple, but do you have any suggestions for figuring out whether it is between two times of day. For example, it is 9:33 AM on a Thursday. So I would need to figure out which scheduled section of the week that time corresponds to. How would I go about comparing the time to set periods during the week, for example an Array of sectioned times during a week such as {Monday from 9-10 AM, Tuesday from 3-4 PM, Thursday from 8-11 AM}, and seeing which section of time the current time falls between?
An efficient way to find which period any date lies within would be to have a class;
public class TimePeriod implements Comparable<TimePeriod>{
Date start;
Date end;
//Constructor, getters, setters
boolean isIn(Date date) {
return date.after(start) && date.before(end);
}
public int compareTo(TimePeriod other) {
return start.compareTo(other.start);
}
}
..and then create a sorted list of TimePeriod where you can perform a binary search.
edit:
This might make the binary search easier;
int check(Date date) {
if (isIn(date)) {
return 0;
} else if (start.after(date)) {
return -1;
} else if (end.before(date)) {
return 1;
} else {
throw new IllegalStateException("Time has gone badly wrong");
}
}
If you're using Date Class, you could do it like this
SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy hh:mm");
Date before = sdf.parse("07/05/2012 08:00");
Date after = sdf.parse("07/05/2012 08:30");
Date toCheck = sdf.parse("07/05/2012 08:15");
//is toCheck between the two?
boolean isAvailable = (before.getTime() < toCheck.getTime()) && after.getTime() > toCheck.getTime();
EDITED
As suggested by Jonathan Drapeau you could also use compareTo.
SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy hh:mm");
Date before = sdf.parse("07/05/2012 08:00");
Date after = sdf.parse("07/05/2012 08:30");
Date toCheck = sdf.parse("07/05/2012 08:15");
//is toCheck between the two?
if you want to include the "initial" and "final" date range
boolean isAvailable = before.compareTo(toCheck) >= 0 && after.compareTo(toCheck) <= 0
if you want to exclude the "initial" and "final" date range
boolean isAvailable = before.compareTo(toCheck) > 0 && after.compareTo(toCheck) < 0
You could use it too on Calendar class.
Anyway, i highly recommend you to use Calendar. It's a way precise class
you could check it like this:
Calendar cal1 = Calendar.getInstance(); // for example 12:00:00
Calendar cal2 = Calendar.getInstance(); // for exmaple 12:30:00
Calendar userTime = Calendar.getInstance(); // time to test: 12:15:00
if(user.after(cal1)&& user.before(cal2)){
//...
}
And to initialize and set times to Calendar, check this:
http://www.tutorialspoint.com/java/util/calendar_settime.htm
I would suggest using the Epoch time.
For a definition of Epoch time: http://en.wikipedia.org/wiki/Epoch_time
Basically, its a number of seconds after a specific date, i believe in 1989. If you translate the 3 times (the current time and the 2 times to compare to) in epoch time you can just use > < = etc.
For information on getting epoch time, Try here (has many languages): http://shafiqissani.wordpress.com/2010/09/30/how-to-get-the-current-epoch-time-unix-timestamp/
Unfortunately, my java is lacking or I'd give you some code :)
Edit:
Java epoch time code:
long epoch = System.currentTimeMillis()/1000;
Because my Java is bad and I don't have an interpreter where I am, I can only suggest using this site to help convert the other dates to epoch time: http://www.epochconverter.com/
There is before(Date) and after(Date) method in Date Class.
secondDate.before(firstDate)
If you use Calendar class, it has explicit before() and after() methods:
Calendar startDate = ...
Calendar endData = ...
isBetween = currentDate.after(startDate) && currentDate.before(endDate);

Check if DAY_OF_WEEK is between Monday and Friday

I'm trying to create a method which is checking if "today" is between Monday and Friday. For this I get with this line 'int day = Calendar.DAY_OF_WEEK;' the actual day. After that I fill a ArrayList with the days (Monday, Tuesday, Wendsday, Thursday and Friday). Now when I check if the actual day is in my ArrayList, i set boolean DAY = true else i set boolean DAY = false. I tryed the Method today and yesterday, but it allways sets the boolean to false.
What do I need to change that my code works? You'll find the code down here.
Code
int day = Calendar.DAY_OF_WEEK;
ArrayList<Integer> daylist = new ArrayList<Integer>();
daylist.add(Calendar.MONDAY);
daylist.add(Calendar.TUESDAY);
daylist.add(Calendar.WEDNESDAY);
daylist.add(Calendar.THURSDAY);
daylist.add(Calendar.FRIDAY);
if (daylist.contains(day)){
DAY = true;
}else{
DAY = false;
}
Wow, that's like trying to kill a mosquito with a thermo-nuclear warhead :-)
Java guarantees (in 1.5) (unchanged up to 1.8 at least) that the values of SUNDAY through SATURDAY are contiguous (1 through 7) so it's a simple matter of checking a range.
However, DAY_OF_WEEK is not the day of the week, it's a field number (with the value 7) to be passed to the getter to retrieve the day of the week. The only time Calendar.DAY_OF_WEEK itself will match an actual day will be on Saturdays.
You can use code such as:
Calendar myDate = Calendar.getInstance(); // set this up however you need it.
int dow = myDate.get (Calendar.DAY_OF_WEEK);
boolean isWeekday = ((dow >= Calendar.MONDAY) && (dow <= Calendar.FRIDAY));
Following this, isWeekday will be true if and only if the day from myDate was Monday through Friday inclusive.
int day = Calendar.DAY_OF_WEEK; should instead be
Calendar cal; // The calendar object
....your other code for getting the date goes here....
int day = cal.get(Calendar.DAY_OF_WEEK);
Your current code just gets the value of the constant Calendar.DAY_OF_WEEK.
This should do the trick for you i assume.
int day = cal.get(Calendar.DAY_OF_WEEK);
if (day >= Calendar.MONDAY && day <= Calendar.FRIDAY){
DAY = true;
}else{
DAY = false;
}
int day = Calendar.DAY_OF_WEEK;
The logic is broken right here. DAY_OF_WEEK is a constant identifying which type of data we need to retrieve from a Calendar instance.
The simplest solution to your problem (since Calendar.FRIDAY > ... > Calendar.MONDAY) is
Calendar now = Calendar.getInstance();
int day = now.get(Calendar.DAY_OF_WEEK);
if (day >= Calendar.MONDAY && day <= Calendar.FRIDAY)
// do something
First Calendar.DAY_OF_WEEK is an integer field will always gives you 7. You need to create an instance of a Calendar like Calendar cal = Calendar.getInstance(); By default it gives you the current date in current timezone.
Then you can call cal.get(Calendar.DAY_OF_WEEK); which will give you any day between Sunday and Sat'day
Now you can check something like this
if(cal.get(Calendar.DAY_OF_WEEK) == Calendar.SUNDAY || cal.get(Calendar.DAY_OF_WEEK) == Calendar.SATURDAY) {
System.out.println("Weekend");
} else {
System.out.println("Weekday");
}
You can apply this logic to your problem!!

Need two Date() values for Java task

This is a really simple request, but I am not quite sure the easiest/most efficient way of generating these two values.
I need to write a script that will check whether a given value is between two values. I am well aware of how this is done in SQL.
The way I need the values is somethign similar to the following.
Date testValue = new Date() //This represents the value we are testing
Date beginningOfDay = .... //This value would represent the date for
testValue at 12:00am
Date endOfDay = ... //This value would represent the date for
testValue at 11:59:59pm
Again, the Java Date() type may not be the best practice to do something like this. In the end I just need to generate three values that I can say
if testValue is after beginningOfDay && testValue is before endOfDay
//do logic
Personally I use the Calendar object for this. For example:
Date testDate = ??? //Replace with whatever source you are using
Calendar testDateCalendar = Calendar.getInstance();
testDateCalendar.setTime(testDate);
Date today = new Date();
Calendar endOfDay = Calendar.getInstance(); //Initiates to current time
endOfDay.setTime(today);
endOfDay.set(Calendar.HOUR_OF_DAY, 23);
endOfDay.set(Calendar.MINUTE, 59);
endOfDay.set(Calendar.SECOND, 59);
Calendar startOfDay = Calendar.getInstance();
startOfDay.setTime(today);
startOfDay.set(Calendar.HOUR_OF_DAY, 0);
startOfDay.set(Calendar.MINUTE, 0);
startOfDay.set(Calendar.SECOND, 0);
if (startOfDay.before(testDateCalendar) && endOfDay.after(testDateCalendar))
{
//Whatever
} else {
//Failure
}
You can use a calendar object to do this and by the way, the way you did the bounds check in your question is wrong (your date can match the before/after dates and still be considered in range). The following shows whether a date falls on a certain day of the year. It assumes that the timezones for the dateTime to check and the day are equal and that no time adjustments took place:
Date dateTime=...
Date day=...
// This is the date we're going to do a range check on
Calendar calDateTime=Calendar.getInstance();
calDateTime.setTime(dateTime);
// This is the day from which we will get the month/day/year to which
// we will compare it
Calendar calDay=Calendar.getInstance();
calDay.setTime(day);
// Calculate the start of day time
Calendar beginningOfDay=Calendar.getInstance();
beginningOfDay.set(calDay.Get(Calendar.YEAR),
calDay.Get(Calendar.MONTH),
calDay.Get(Calendar.DAY_OF_MONTH),
0, // hours
0, // minutes
0); // seconds
// Calculate the end of day time
Calendar endOfDay=Calendar.getInstance();
endOfDay.set(calDay.Get(Calendar.YEAR),
calDay.Get(Calendar.MONTH),
calDay.Get(Calendar.DAY_OF_MONTH),
23, // hours
59, // minutes
59); // seconds
// Now, to test your date.
// Note: You forgot about the possibility of your test date matching either
// the beginning of the day or the end of the day. The accepted answer
// got this range check wrong, as well.
if ((beginningOfDay.before(calDateTime) && endOfDay.after(calDateTime)) ||
beginningOfDay.equals(calDateTime) || endOfDay.equals(calDateTime))
{
// Date is in range...
}
This can be further simplified to:
Date dateTime=...
Date day=...
// This is the date we're going to do a range check on
Calendar calDateTime=Calendar.getInstance();
calDateTime.setTime(dateTime);
// This is the day from which we will get the month/day/year to which
// we will compare it
Calendar calDay=Calendar.getInstance();
calDay.setTime(day);
if (calDateTime.get(YEAR)==calDay.get(YEAR) &&
calDateTime.get(MONTH)==calDay.get(MONTH) &&
calDateTime.get(DAY_OF_YEAR)==calDay.get(DAY_OF_YEAR))
{
// Date is in range
}
Here's something I've used in my own code to determine if a file was modified on a certain day. Like the other answers in this thread, I used the Calendar.
// Get modified date of the current file
// and today's date
Calendar today = Calendar.getInstance();
Calendar modDate = Calendar.getInstance();
Date date = new Date(file.lastModified());
modDate.setTime(date);
// Convert dates to integers
int modDay = modDate.get(Calendar.DAY_OF_YEAR);
int todayDay = today.get(Calendar.DAY_OF_YEAR);
if (modDay == todayDay) {
// Do stuff
}
This might be closer to what you are looking for since you only need to see if the event falls on a certain day.

Java Date & Time of Day

I have an application that passes in java.util.Date. I want to check whether this date is within a specified time of day (e.g. between 10:30 & 11:30), I don't care about the date, just the time of day.
Can anyone show me a simple way to do this?
Thanks
This is what the Calendar class is for. Assuming date is your Date object:
Calendar cal = Calendar.getInstance();
cal.setTime(date);
int hour = cal.get(Calendar.HOUR_OF_DAY);
int minutes = cal.get(Calendar.MINUTE);
if (hour == 10 && minutes >= 30 || hour == 11 && minutes <= 30) {
...
}

Categories