I have the following set and need to compare its date instance with the current date. Although both dates are the same but the comparison returns false !!
MyClass.java
import java.util.Date;
public class MyClass {
private Date date;
...
}
My Code
....
Set <MyClass> myclass = new HashSet();
I populate it with some data here...
for(MyClass m : myclass)
{
System.err.println("date>>:" + trim(m.getDate())); //returns 2013-08-08
System.err.println("date>>:" + trim(getCurrentDate())); //returns 2013-08-08
System.err.println("boolean:" +
trim(m.getDate()).equals(trim(getCurrentDate()))); //returns false
}
}
public Date getCurrentDate() {
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
Date date = new Date();
dateFormat.format(date));
return date;
}
public Date trim(Date date){
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
calendar.set(Calendar.MILLISECOND, 0);
calendar.set(Calendar.SECOND, 0);
calendar.set(Calendar.MINUTE, 0);
calendar.set(Calendar.HOUR, 0);
return calendar.getTime();
}
Dates are not same, they may differ by millis/sec. Date equals doesn't depend upon format of date but compares value. Below code would return false as well:
Date d1 = new Date();
SimpleDateFormat f = new SimpleDateFormat("yyyy-mm-dd");
Date d2 = new Date();
f.format(d2);
System.out.println(d1);//e.g. Thu Aug 08 12:09:24 IST 2013
System.out.println(d2);//e.g. Thu Aug 08 12:09:26 IST 2013
System.out.println(d1.equals(d2));//false
Date.equals compares time (Date.getTime()), equals will return true only if they matches:
public boolean equals(Object obj) {
return obj instanceof Date && getTime() == ((Date) obj).getTime();
}
Per javadoc:
The result is true if and only if the argument is not null and is a Date object that represents the same point in time, to the millisecond, as this object.
Thus, two Date objects are equal if and only if the getTime method returns the same long value for both.
Date.getTime return the number of milliseconds since January 1, 1970, 00:00:00 GMT
So in you updated question with trim, consider you are comparing two long values of time in millis.
If you require to compare yyyy-MM-dd values of two different date instances, consider using String.equals instead (hack way):
SimpleDateFormat f = new SimpleDateFormat("yyyy-MM-dd");
String date1 = f.format(new Date());//2013-08-08
String date2 = f.format(new Date());//2013-08-08
System.out.println(date1.equals(date2));
Each time you call getCurrentDate, you might receive a new date. Formatting it the way you do is essentially a no-op and the date still carries its hours, minutes, seconds and milliseconds.
So they are actually proably different for real.
You could remove this extra information to get the desired behaviour.
The Date class includes the time of the day to millisecond precision, and the time counts when comparing for equality.
To compare only the "date" part you can do one of several things, for example format the dates as year-month-day and compare the resulting strings, or create Calendar objects from the dates and compare the year, month and day individually. Another option is to make sure the Dates you compare have the same hour of the day, for example 12:00, that way you can use the equals method.
You can use GregorianCalendar and Calendar#get(..) to only compare year, month, and day.
There is a perfect sample from the javadoc :
// get the supported ids for GMT-08:00 (Pacific Standard Time)
String[] ids = TimeZone.getAvailableIDs(-8 * 60 * 60 * 1000);
// if no ids were returned, something is wrong. get out.
if (ids.length == 0)
System.exit(0);
// begin output
System.out.println("Current Time");
// create a Pacific Standard Time time zone
SimpleTimeZone pdt = new SimpleTimeZone(-8 * 60 * 60 * 1000, ids[0]);
// set up rules for Daylight Saving Time
pdt.setStartRule(Calendar.APRIL, 1, Calendar.SUNDAY, 2 * 60 * 60 * 1000);
pdt.setEndRule(Calendar.OCTOBER, -1, Calendar.SUNDAY, 2 * 60 * 60 * 1000);
// create a GregorianCalendar with the Pacific Daylight time zone
// and the current date and time
Calendar calendar = new GregorianCalendar(pdt);
Date trialTime = new Date();
calendar.setTime(trialTime);
// print out a bunch of interesting things
System.out.println("ERA: " + calendar.get(Calendar.ERA));
System.out.println("YEAR: " + calendar.get(Calendar.YEAR));
System.out.println("MONTH: " + calendar.get(Calendar.MONTH));
System.out.println("WEEK_OF_YEAR: " + calendar.get(Calendar.WEEK_OF_YEAR));
System.out.println("WEEK_OF_MONTH: " + calendar.get(Calendar.WEEK_OF_MONTH));
System.out.println("DATE: " + calendar.get(Calendar.DATE));
System.out.println("DAY_OF_MONTH: " + calendar.get(Calendar.DAY_OF_MONTH));
System.out.println("DAY_OF_YEAR: " + calendar.get(Calendar.DAY_OF_YEAR));
System.out.println("DAY_OF_WEEK: " + calendar.get(Calendar.DAY_OF_WEEK));
System.out.println("DAY_OF_WEEK_IN_MONTH: "
+ calendar.get(Calendar.DAY_OF_WEEK_IN_MONTH));
System.out.println("AM_PM: " + calendar.get(Calendar.AM_PM));
System.out.println("HOUR: " + calendar.get(Calendar.HOUR));
System.out.println("HOUR_OF_DAY: " + calendar.get(Calendar.HOUR_OF_DAY));
System.out.println("MINUTE: " + calendar.get(Calendar.MINUTE));
System.out.println("SECOND: " + calendar.get(Calendar.SECOND));
System.out.println("MILLISECOND: " + calendar.get(Calendar.MILLISECOND));
System.out.println("ZONE_OFFSET: "
+ (calendar.get(Calendar.ZONE_OFFSET)/(60*60*1000)));
System.out.println("DST_OFFSET: "
+ (calendar.get(Calendar.DST_OFFSET)/(60*60*1000)));
Actually there is a problem in your method..
public Date getCurrentDate() {
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
Date date = new Date();
dateFormat.format(date);
return date;
}
dateFormat.format(date) will return a String date in yyyy-MM-dd format but you are returning date from this method which will return the Date in 'Thu Aug 08 12:21:34 IST 2013' this format not in '2013-08-08' this. So you should take the String as return from this method and then compare it by equals.
Try this, I think this should help you.
Related
Calendar cl = Calendar.getInstance(TimeZone.getTimeZone("America/Los_Angeles"));
cl.setTimeInMillis(time);
Toast.makeText(getActivity(), cl.getTime().toString(), Toast.LENGTH_LONG).show();
What ever time I put it always returns the time in EST. I want it to return the time in PST. Does anyone know that could posibly be wrong?
P.S.
My local time is EST.
Try this:
TimeZone.setDefault(TimeZone.getTimeZone("PST"));
Calendar cl = Calendar.getInstance();
This isn't really an answer but it's too big to put into a comment. This is what I found.
My test looked like this
TimeZone tz = TimeZone.getTimeZone("America/Los_Angeles");
Calendar cl = Calendar.getInstance(tz);
System.out.println(tz.getDisplayName());
String dayname = cl.getDisplayName(Calendar.DAY_OF_WEEK,Calendar.SHORT,Locale.US);
String monthname = cl.getDisplayName(Calendar.MONTH,Calendar.SHORT,Locale.US);
int hour = cl.get(Calendar.HOUR);
int min = cl.get(Calendar.MINUTE);
int sec = cl.get(Calendar.SECOND);
int mill = cl.get(Calendar.MILLISECOND);
int year = cl.get(Calendar.YEAR);
System.out.println("Time = " + cl.getTime().toString());
System.out.println("Manually = " +
dayname + " " + monthname + " " +
hour + ":" + min +":" + sec + ":" + mill + " " +
cl.getTimeZone().getDisplayName(Locale.US) + " " + year);
Which gave the output
Pacific Standard Time
Time = Tue Nov 05 11:36:33 EST 2013
Manually = Tue Nov 8:36:33:238 Pacific Standard Time 2013
Looking at Calendar.getTime():
public final Date getTime() {
return new Date(getTimeInMillis());
}
Following the bouncing ball...
public long getTimeInMillis() {
if (!isTimeSet) {
updateTime();
}
return time;
}
private void updateTime() {
computeTime();
// The areFieldsSet and areAllFieldsSet values are no longer
// controlled here (as of 1.5).
isTimeSet = true;
}
But I don't have the source for computTime() so that's where I stopped.
Gabriel's answer works, fwiw.
Calendar.getTime() returns a java Date instance which represents the number of milliseconds from the epoch January 1, 1970, 00:00:00 GMT. Calling toString() on a Date instance will print the date based on the timezone configured on the server. To properly format a date for output in another timezone, you'll want to look at using a date formatter.
TimeZone est = TimeZone.getTimeZone("America/New_York");
Calendar cal = Calendar.getInstance(est);
DateFormat formatter = new SimpleDateFormat("EEE MMM dd HH:mm:ss zzz yyyy");
formatter.setTimeZone(est);
System.out.println(formatter.format(cal.getTime()));
Date date1= new java.util.Date();
java.sql.Date Sqldob = new java.sql.Date(date1.getTime());
System.out.println("date" +Sqldob);
Time Sqldob1 = new Time(date1.getTime());
System.out.println("User Time: " +Sqldob1);
String yourTime="09:30:00";
SimpleDateFormat ra = new SimpleDateFormat("HH:mm:ss");
Date yourDate = ra.parse(yourTime);
Time sqlTime3 = new Time(yourDate.getTime());
System.out.println("your time"+sqlTime3);
if(Sqldob1.before(sqlTime3)){
Sqldob1 = sqlTime3;
System.out.println("inside loop");
}
In the code above I am comparing two time variables for equality, but it is giving me the same value -1 for all the types of input
You need to use the Date#before(Date),Date#after(Date) and Date#equals(Date) methods for basic date comparisons.
E.g:
Date d1 = new Date();
Date d2 = new Date();
if(d1.after(d2)){
// Do something
}
if(d1.before(d2)){
// Do something
}
if(d1.equals(d2)){
// Do something
}
You can use the Date#compareTo(Date) method also, but then, you need to interpret the output of the compareTo method accordingly.
As the docs say:
The value 0 if the argument Date is equal to this Date; a value less
than 0 if this Date is before the Date argument; and a value greater
than 0 if this Date is after the Date argument.
In your case, you are getting -1 because
new SimpleDateFormat("HHH:mm:ss"); is wrong. Should be new SimpleDateFormat("HH:mm:ss");
int compare= sqlTime3.compareTo(Sqldob1); This sqlTime3 has only time in it. The date is the epoch date as you've not mentioned that, and hence, its always going to be before new Date() which is today.
Your solution:- (Hope this addresses your problem)
java.util.Date date1= new java.util.Date();
Time Sqldob1 = new Time(date1.getTime());
System.out.println("User Time: " +Sqldob1);
Calendar cal = Calendar.getInstance();
cal.set(Calendar.HOUR_OF_DAY, 19); // Your hour
cal.set(Calendar.MINUTE, 30); // Your Mintue
cal.set(Calendar.SECOND, 00); // Your second
Time sqlTime3 = new Time(cal.getTime().getTime());
System.out.println("your time: "+sqlTime3);
if(Sqldob1.before(sqlTime3)){
Sqldob1 = sqlTime3;
System.out.println("inside loop");
}
You need to parse the date and call methods like before(), after() and equals() like this,
if(date.before(date1)){
System.out.println(" date is before date1 ");
}
if(date.after(date1)){
System.out.println(" date is after date1 ");
}
If both date and date1 are equal you can use equals method,
if(date.equals(date1)){
System.out.println(" date and date1 are equal");
}
Modern version:
LocalDateTime dateTime1 = LocalDateTime.now(ZoneId.systemDefault());
LocalDate dob = dateTime1.toLocalDate();
System.out.println("date " + dob);
LocalTime dob1 = dateTime1.toLocalTime();
System.out.println("User Time: " + dob1);
String yourTime = "09:30:00";
LocalTime time3 = LocalTime.parse(yourTime);
System.out.println("your time " + time3);
if (dob1.isBefore(time3)) {
dob1 = time3;
System.out.println("inside if statement");
}
When I ran this code this morning, it printed:
date 2017-07-07
User Time: 05:32:01.881
your time 09:30
inside if statement
The point is: With the old and now long outdated classes Date and Time it is easy not to get things right. With the modern classes I use here, it’s much easier to get them right.
Are you using java.sql types because you really need to get your date and time from a database and/or store them into one? This was what these were for, you shouldn’t really have used them for other purposes. I use “was” and “were” intentionally because you don’t need them for this purpose either anymore. With a new JDBC driver, you can get a LocalDateTime from the database and store one back, or depending on your column datatype get an Instant and convert it to LocalDateTime:
LocalDateTime dateTime2 = instantFromDb.atZone(ZoneId.systemDefault())
.toLocalDateTime();
PS Item 2. in SoduRahul’s answer gives the real and correct explanation of what went wrong in your program: though Time was meant for time-of-day only, your Sqldob1 ends up holding today’s date and sqlTime3 the date of the epoch (January 1, 1970), so the former will always be after the latter by their before method.
compareTo() method always return zero for equal and non-zero for unequal dates.
I'm facing a really strange problem I haven't seen before. I have a date in milliseconds and want to display it as a readable date. This is my code:
if (validUntil == 0) {
return activity.getResources().getString(R.string.forever);
} else {
Date startDate = new Date(validFrom);
Date endDate = new Date(validUntil);
if (startDate.compareTo(endDate) < 0) {
String date = sdf.format(startDate) + " - " + sdf.format(endDate);
return date;
} else if (startDate.compareTo(endDate) == 0) {
return activity.getResources().getString(R.string.forever);
}
}
As you can see I just want to create a string which shows the time span. When I debug into my code, the date objects contain the right values while sdf.format(...) gives me an invalid date.
Example:
startdate in milliseconds: 1375017555000
startdate object contains: Sun Jul 28 15:19:15 CEST 2013
sdf.format(startDate) returns: 28.19.2013
I get a simillar result for the end date.
What am I doing wrong?
Probably it seems you have used mm to denote months , but it should be MM . Look at the documentation.
M month in year
m minute in hour
Try:
SimpleDateFormat sdf = new SimpleDateFormat("dd.MM.yyyy");
You get minutes instead of months. Your pattern should be like this: "dd.MM.yyyy"
Looks like your date format string is incorrect. This works:
public static void dateFormat(){
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
System.out.println(format.format(new Date()));
}
Result:
2013-07-29
I'm trying to compare two dates with the current date. It seems not to work when I try to know if a date is the same as the current date. Here's what I do in my code :
//BeginDate is set earlier
Date myDate= new SimpleDateFormat("dd/MM/yyyy").parse(BeginDate);
Date now = new Date();
System.out.println("Now : " + now);
System.out.println("myDate : " + myDate);
System.out.println("equals : " + myDate.equals(now));
System.out.println(myDate.compareTo(now));
And I get this in the console :
Now : Thu Dec 29 00:28:45 CET 2011
myDate : Thu Dec 29 00:00:00 CET 2011
equals : false
-1
The first comparison should return true and the second "0" right ? Or am I missing something ?
Comparing dates with either equals() or compareTo() compares the times (hours, minutes, seconds, millis) as well as the dates. Your test is failing because myDate is midnight today, whereas now is a little later than that.
Your comparison is failing because you need to format now so that both dates have the same format and thus may be compared.
Or, if you prefer, you can convert dates into strings and perform the comparison:
String beginDate = "28/12/2011";
Calendar now = Calendar.getInstance();
DateFormat df = new SimpleDateFormat("dd/MM/yyyy");
String nowStr = df.format(new Date());
System.out.println("equals : " + beginDate.equals(nowStr));
Are you specifying the milliseconds when creating the dates? If you are, don't. So when creating the dates earlier, only specify the Day, Hour etc, not seconds/milliseconds.
And, change the SimpleDateFormat respectively. That "should" work.
Date object in Java is nothing but a number that represents milliseconds since January 1, 1970, 00:00:00 GMT. It doesn't have any attribute called day, date, month, year etc. That's because date, month, year varies based on the type of calendar and timezone. These attributes belong to Calendar instance.
So, if you have 2 Date objects and you want to compare day of month, month and year then you should create corresponding Calendar instance and compare them separately.
// Parse begin date
DateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy");
Date beginDate = dateFormat.parse(beginDateAsString);
// Create calendar instances
Calendar beginDateCalendar = Calendar.getInstance();
beginDateCalendar.setTime(beginDate);
Calendar todayCalendar = Calendar.getInstance();
// Check Equals
boolean dayEquals = todayCalendar.get(Calendar.DAY_OF_MONTH) == beginDateCalendar
.get(Calendar.DAY_OF_MONTH);
boolean monthEquals = todayCalendar.get(Calendar.MONTH) == beginDateCalendar
.get(Calendar.MONTH);
boolean yearEquals = todayCalendar.get(Calendar.YEAR) == beginDateCalendar
.get(Calendar.YEAR);
// Print Equals
System.out.println(dayEquals && monthEquals && yearEquals);
Above code is cumbersome for the current problem but explains how date operations must be done in JAVA.
If you just want to solve the equals problem you have mentioned then the code below will suffice:
String todayAsString = (new SimpleDateFormat("dd/MM/yyyy")).format(new Date());
System.out.println(beginDateAsString.equals(todayAsString));
If you are only going to be dealing with dates between the years 1900 and 2100, there is a simple calculation which will give you the number of days since 1900:
public static int daysSince1900(Date date) {
Calendar c = new GregorianCalendar();
c.setTime(date);
int year = c.get(Calendar.YEAR) - 1900;
int month = c.get(Calendar.MONTH) + 1;
int days = c.get(Calendar.DAY_OF_MONTH);
if (month < 3) {
month += 12;
year--;
}
int yearDays = (int) (year * 365.25);
int monthDays = (int) ((month + 1) * 30.61);
return (yearDays + monthDays + days - 63);
}
Thus, Date (only) comparison can be achieved by checking if the number of days since 1900 of the 2 dates are equal.
NOTE: The above method should have code added to check if the dates are outside the valid range (1/1/1900 - 31/12/2099) and throw an IllegalArgumentException.
And don't ask me where this calculation came from because we've used it since the early '90s.
public Date getCurrentDay() {
Calendar cal = Calendar.getInstance();
Date date = java.sql.Date.valueOf(
cal.get(cal.YEAR) + ":" +
cal.get(cal.MONTH) + ":" +
cal.get(cal.DATE) );
return date;
}
I need to make a database query where CLIENT says he wants info of next 3 days, here is my method for getting the current day, so I can get todays info, but when my client wants next 3 days, how can I make the query. How do I get the next X days?
You can call cal.add(cal.DATE, 3); to get the same time 3 days later.
You could do a method like the following:
public Date getDaysFromNow(int days) {
Calendar cal = Calendar.getInstance();
cal.add(Calendar.DATE, days);
Date date = java.sql.Date.valueOf(
cal.get(cal.YEAR) + ":" +
cal.get(cal.MONTH) + ":" +
cal.get(cal.DATE) );
return date;
}
public Date getCurrentDay() {
return getDaysFromNow(0);
}
Edit:
Note that you can also set the time to 0 and then call getTimeInMillis(), i.e.
public Date getDaysFromNow(int days, boolean endOfDay) {
Calendar cal = Calendar.getInstance();
cal.set(Calendar.HOUR_OF_DAY, endOfDay ? 23 : 0);
cal.set(Calendar.MINUTE, endOfDay ? 59 : 0);
cal.set(Calendar.SECOND, endOfDay ? 59 : 0);
cal.set(Calendar.MILLISECOND, endOfDay ? 999 : 0);
cal.add(Calendar.DATE, days);
Date date = new java.sql.Date( cal.getTimeInMillis() );
return date;
}
The endOfDay parameter is used to set the time to 23:59:59,999, thus you could get two dates for today: 2011-29-04 00:00:00,000 and 2011-29-04 23:59:59,999 with the same method.
In postgres you can use now() to get the current time. You can then use a string expression to get + 3 days.
You can play with these expressions in a postgres client.
SELECT now() + '3 days'
If your client is in Java, you can just make a helper method to get the days ahead of the current time.:
public Date getDaysAheadCurrentDate(int numberOfDaysAhead) {
if (numberOfDaysAhead <= 0) {
throw new IllegalArgumentException("The number of days ahead must be a positive integer.");
}
Calendar cal = Calendar.getInstance();
// add the number of days before creating the java.sql.Date instance.
cal.add(Calendar.DATE, numberOfDaysAhead);
Date date = java.sql.Date.valueOf(
cal.get(Calendar.YEAR) + ":" +
cal.get(Calendar.MONTH) + ":" +
cal.get(Calendar.DATE) );
return date;
}