I have a time in string format like "02:00" in 24 hours and I want to check it between two other time,such that "07:00"and "15:oo" .How can I check for this, as the time is in string format ?
I use the following code:
SimpleDateFormat simpDate = new SimpleDateFormat("kk:mm");
String s2=simpDate.format(date);
JLabel1.setText(s2);
now I want to check if that String s2 is inbetween "7:00" and "15:00" then set the value to another JLabel named JLabel2 as: "First Shift"
You use a SimpleDateFormat to convert the String to a Date. Then you can compare the dates together.
Read more about SimpleDateFormat here.
First, you need to parse your strings to Date object instances. You can use the DateFormat derived classes to do so (i.e. SimpleDateFormat).
Then, you can do comparisons using the millisecond-representation of both dates (obtained via getTime()) or just compare them using either after(Date date) or before(Date date).
If you need more complex operations you should use the Calendar class.
Besides, if your project works a lot with dates I'd suggest using Joda Time
EDIT (in response to comment):
Using Calendar class it would be this way. First you need a calendar instance for your 7:00 date:
Calendar cal1 = Calendar.getInstance();
cal1.set(Calendar.DATE, 12); // The day of month you are working with
cal1.set(Calendar.MONTH, 7); // The month of the year
cal1.set(Calendar.YEAR, 2012); // The year
cal1.set(Calendar.HOUR_OF_DAY, 7); // Hour in 24-hours fashion
cal1.set(Calendar.MINUTE, 0); // self-explanatory
cal1.set(Calendar.SECOND, 0);
Date shiftStart = cal1.getTime();
Then do the same for the end of the shift:
Calendar cal2 = Calendar.getInstance();
cal2.set( ... ); // Repeat almost every field from previous snippet
cal2.set(Calendar.HOUR_OF_DAY, 15); // Hour in 24-hours fashion
Date shiftEnd = cal2.getTime();
Then, you just need to check the date you want to compare is between those:
Date myDate = ... // the date you want to compare
boolean checkShift = myDate.after(shiftStart) && myDate.before(shiftEnd);
Anyway, as I already said, if you will work with dates a lot in you project I would use Joda Time, as it will ease a lot date handling.
Related
I have a class which contains a variable
private GregorianCalendar cal;
Now I want to initialize it with a date in yyyy-mm-dd format, I tried using the default constructor but the output I get is something like this "2017-05-25T14:36:52+03:00", I only want "2017-05-25" date part?
How do I achieve it?
First, you may hate me for reiterating, you need to understand that there’s a difference between a date and a string representation of that date; a difference between the fundamental data and a string representation of it.
Second, you can use LocalDate (and the other Java date and time classes) with Java 7 if you want. It is (and they are all) in the ThreeTen-Backport , a back-port of the Java SE 8 date-time classes to Java SE 6 and 7.
Since I gather that LocalDate fits your requirements much better, I really think you should give it a thought or two. So instead of your cal I suggest
private LocalDate date = LocalDate.now(ZoneId.systemDefault());
Also think about whether you want the current time zone setting of your JVM (as the above will give you) or you want to control which time zone you use. It will make a difference.
Finally, if you really insist. As you have understood by now, I cannot give you a string in a GregorianCalendar. You may discard the time part of your GregorianCalendar so you only have the date part. And you may format it into a string of your liking.
public class GregorianCalendarDemo {
private GregorianCalendar cal;
public GregorianCalendarDemo() {
cal = new GregorianCalendar(TimeZone.getDefault(), Locale.getDefault());
// discard time of day so we only have the date
cal.set(Calendar.HOUR_OF_DAY, cal.getActualMinimum(Calendar.HOUR_OF_DAY));
cal.set(Calendar.MINUTE, cal.getActualMinimum(Calendar.MINUTE));
cal.set(Calendar.SECOND, cal.getActualMinimum(Calendar.SECOND));
cal.set(Calendar.MILLISECOND, cal.getActualMinimum(Calendar.MILLISECOND));
}
protected GregorianCalendar getCal() {
return cal;
}
public String getFormattedCal() {
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
return format.format(getCal().getTime());
}
}
When I just called getFormattedCal(), it returned 2017-05-25.
Again, decide whether default values for time zone and locale are fine or you want something else.
You might have thought that we could discard the hours with just cal.set(Calendar.HOUR_OF_DAY, 0):, and similarly with minutes and seconds. It would work in 99 % of all cases at least. However, with transistion to summer time (daylight savings time), the day is not guaranteed to begin at 0 hours, so the above code is more bulletproof.
Link
ThreeTen Backport home
You can try to use SimpleDateFormat for example :
GregorianCalendar cal = new GregorianCalendar();
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
format.setCalendar(cal);
String result = format.format(cal.getTime());
System.out.println(result);//today is 2017-05-25
To convert String to GregorianCalendar :
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd'T'hh:mm:ssX");
Date date = format.parse("2017-05-25T14:36:52+03:00");
GregorianCalendar cal2 = new GregorianCalendar();
cal2.setTime(date);
I see plenty of questions for taking a GregorianCalendar or Date object and printing a "yyyyMMdd"-formatted string.
However, I want to go the opposite direction.
I have a "yyyyMMdd"-formatted string, and I want to create a GregorianCalendar object.
I could easily parse this and call a series of .set() methods, but I was wondering if there was a slick-and-easy way.
You can use a SimpleDateFormat like so:
SimpleDateFormat format = new SimpleDateFormat("yyyyMMdd");
Date date = format.parse("20150119");
Calendar calendar = GregorianCalendar.getInstance();
calendar.setTime(date);
Can anyone tell me why the date is being set to next month instead of this month?
Even though im setting the dateFormatted variable as "28/08/2014" its setting the date to "28/07/2014".
I can simply go -1 at the month but it will mess up the date in January.
Is there some other way i should be setting the date?
Thanks
UtilDateModel model;
JDatePanelImpl datePanel;
DatePickerImpl datePicker;
model = new UtilDateModel();
model.setDate(yearInt, monthInt, dayInt);
model.setSelected(true);
datePanel = new JDatePanelImpl(model);
datePicker = new JDatePickerImpl(datePanel);
// String dateFormatted = (String) result[1];
String dateFormatted = "28/08/2014";
System.out.println("Date Formatted : " + (String) result[1]);
int day = Integer.parseInt(dateFormatted.substring(0, 2)); // Correct
int month = Integer.parseInt(dateFormatted.substring(3, 5)); // Correct
int year = Integer.parseInt(dateFormatted.substring(6, 10)); // Correct
System.out.println(day);
System.out.println(month);
System.out.println(year);
model.setDate(year, month, day);
model.setSelected(true);
You're doing date parsing wrong, please use a SimpleDateFormat or the like
The problem that you are seeing is probably related to the fact that some fields are 0-based and some are 1-based.
UPDATE
Dates should not be stored as strings in the database, instead use the available date types.
Date parsing in general is much trickier than you might think. DST, leap years, language,... all comes into play.
The newest java iteration has a complete rewrite for date handling based on joda time (http://www.joda.org/joda-time/) but you can also use the "old" way of date parsing in java which is not bad, simply different.
You should look at the javadoc of SimpleDateFormat, it will tell you why you need lower case "yyyy" for example and upper case "MM". The formatter will give you a Date which you can probe with Calendar for the required fields.
All the while it will take into account all the niggling details about date handling.
I'm not known with the 'JDatePicker' package, but after doing some research, i've found this, please read article 3 on this page. It says month number is 0 based, so januari should be 0 ( 1st month minus 1).
I am trying to compare dates in two different formats:
Tue Jul 01 00:12:14 EST 2014
which is created using the function:
private Date getDate (int day, int month, int year){
Calendar calendar = Calendar.getInstance();
calendar.setLenient(false);
calendar.set(year, month-1, day);
Date date = calendar.getTime();
return date;
}
and
2014-07-01
After comparing these two dates, I would like the output to show that they are equal. However I BELIEVE, because of the timestamp in the 1st Date, they are not being determined as equal.
Is my assumption correct?
If so, is there a way that I could convert the first date into the second? The second Date is being retrieved from an SQL database where the variable is DATE.
Thank you for your help.
It sounds like you are comparing a java.util.Date (an instant in time) with a java.sql.Date (an instant in time whose time of day is midnight).
Arithmetic rounding must deal with the local timezones, making it more complex than you might first think.
The simplest way to compare the two would be to use a data formatter and compare the output:
SimpleDateFormat f = new SimpleDateFormat("yyyy-MM-dd");
if (f.format(date1).equals(f.format(date2))) {
// the two dates are on the same "day"
}
java.sql.Date Has Zero Time
The documentation explains that a java.sql.Date has its time portion set to zero (UTC), meaning midnight.
So when comparing to a java.util.Date with a non-zero time-of-day, the two will not be equal.
LocalDate
So much easier using Joda-Time of the new java.time package in Java 8. Both offer a LocalDate class that ignores time-of-day.
LocalDate x = new LocalDate( 2014, 5, 6 );
LocalDate y = new LocalDate( 2014, 5, 6 );
boolean same = x.equals( y );
To convert your java.sql.Date to a Joda-Time LocalDate, pass it to the constructor of New LocalDate. You may need to also pass DateTimeZone.UTC to be sure it is not interpreted by your JVM's default time zone.
Is my assumption correct?
Yes, your assumption is correct. Two Date instances are correct if both their getTime() results are the same
from Date.java
public boolean equals(Object obj) {
return obj instanceof Date && getTime() == ((Date) obj).getTime();
}
Converting just assumes you need to set the hours,minutes and seconds to 0:
calendar.set(Calendar.HOUR_OF_DAY,0);
calendar.set(Calendar.MINUTE,0);
calendar.set(Calendar.SECOND,0);
Assuming that both dates are in the same timezone and also assuming that the date equality criteria here is the day of the year, I believe you can just compare the date as strings.
To do that, you can use SimpleDateFormat to ensure both are in the same format.
I would suggest you convert both of them to one particular format and compare them using a Comparator.
If you need to check whether two dates are equal, the best way is to use compareTo method.
if(yesterday.compareTo(today) == 0) {
System.out.println("Given dates are same");
} else {
System.out.println("Given dates are different ");
}
Read more: https://www.java67.com/2016/09/how-to-compare-two-dates-in-java.html#ixzz6uH5r1xE2
This question already has answers here:
Comparing two java.util.Dates to see if they are in the same day
(14 answers)
Closed 6 years ago.
I have a problem with Date instance. I did the following:
Date startDate = new Date(); //this is from database value
Date todayDate = new Date(); //this is created locally
Now when am trying to compare them, the only issue is that the Date instance will have time, so when I check if they are equal it probably wouldn't give the same thing I expect, but rather less or more. I tested the following:
System.out.println(rsv.startDate);
System.out.println("Today date:"+todayDate);
if(rsv.startDate.equals(todayDate)){
System.out.println("Equal!");
}else if(rsv.startDate.after(todayDate)){
System.out.println("After!!");
}else{
System.out.println("Before!!!!");
}
and although both are 5th feb but it shows output of Before instead of equal. How can I remedy this? I know about SimpleDateFormat but that would change the date to strings.
Thanks,
For Date operation you can use Joda utility. Following snippet code shows compare two date :
DateTime one = new DateTime(original-Date-1);
DateTime two = new DateTime(original-Date-2);
LocalDate oneDate = one.toLocalDate();
LocalDate twoDate = two.toLocalDate();
return oneDate.compareTo(twoDate);
You can see: http://joda-time.sourceforge.net/index.html
You can strip out the time from the current Date object:
Date date = new Date();
Calendar dCal = Calendar.getInstance();
dCal.setTime(date);
dCal.set(Calendar.HOUR_OF_DAY, 0);
dCal.set(Calendar.MINUTE, 0);
dCal.set(Calendar.SECOND, 0);
dCal.set(Calendar.MILLISECOND, 0);
date = dCal.getTime();
And then make your comparision.
Alternatively, if you need in your project more date/time processing power, you can use joda date time library: http://joda-time.sourceforge.net
MidnightDate class is suitable for this specific usecase: http://joda-time.sourceforge.net/api-release/org/joda/time/DateMidnight.html
Date contains both the date and time. Equals() will only return true if the time is also the same. To make the comparison work, you need to make sure that the time portion of both Date objects is the same (eg all set to zero).