Java Joda time isAfter date solution - java

I want to compare two dates.
If the current date time is greater or after the
specific date , then it will return 'True'.
So far I have tried this.
String deadline = "25/11/2017 11:00:00";
DateTime utc = new DateTime(DateTimeZone.UTC);
DateTimeZone timeZone = DateTimeZone.forID("Asia/Dhaka");
DateTime dhakaTime = utc.toDateTime(timeZone);
//Dead Line Time
DateTimeFormatter format = DateTimeFormat.forPattern("dd/MM/yyyy HH:mm:ss");
DateTime deadlineTime = format.parseDateTime(deadline.trim());
//Comapare
return deadlineTime.isAfter(dhakaTime.plusDays(2));
As today is 23 and dhakaTime.plusDays(2) will be 25 so it should return
"true".
But I am getting "false".
Output value :
dhakaTime.plusDays(2) = 2017-11-25T14:10:27.762+06:00
deadlineTime = 2017-11-25T11:00:00.000+06:00
Am i missing something or doing something wrong?

It gives false correctly.
You're comparing
deadLineTime = 2017-11-25T11:00:00.000+06:00 and
dhakaTime(+2) = 2017-11-25T14:10:27.762+06:00
They both are at same date, but with time, deadLineTime is at 11AM but dhakaTime(+2) is at 2PM. So,
(Nov 25, 2017 11AM)isAfter(Nov 25, 2017 2PM) is false.
EDIT: Testcases
As you mentioned you're testing, The following used different test cases for comparing deadLine with dhakaTime (+1, and +2 days). I hope this gives you an idea about how this works.
public static void main(String[] args) {
String deadline = "25/11/2017 11:00:00";
DateTime utc = new DateTime(DateTimeZone.UTC);
DateTimeZone timeZone = DateTimeZone.forID("Asia/Dhaka");
DateTime dhakaTime = utc.toDateTime(timeZone);
//Dead Line Time
DateTimeFormatter format = DateTimeFormat.forPattern("dd/MM/yyyy HH:mm:ss");
DateTime deadlineTime = format.parseDateTime(deadline.trim());
System.out.println("Deadline : " + deadline);
System.out.println("Current datetim : " + dhakaTime);
System.out.println("current datetime + 1 day : " + dhakaTime.plusDays(1));
System.out.println("current datetime + 2 day : " + dhakaTime.plusDays(2));
System.out.println("Is deadline after current datetime:" + deadlineTime.isAfter(dhakaTime));
System.out.println("Is deadline after current datetime + 1 day:" + deadlineTime.isAfter(dhakaTime.plusDays(1)));
System.out.println("Is deadline after current datetime + 2 day:" + deadlineTime.isAfter(dhakaTime.plusDays(2)));
}

Try using the method DateTimeFormatter withZone(DateTimeZone zone) and use that to create the DateTime

Related

UTC-N to Local Time

Using joda, how do you format a UTC+/-n time, to "wall time" to be displayed to the user:
From (UTC+/-n):
2015-05-15T03:28:49.523-04:00
To (EST) Wall:
2015-05-14 23:22:44
Update (1)
Please consider the following code. We need to use timestamp
for writes to and from the DB in UTC. With that in mind:
DateTimeZone.setDefault(DateTimeZone.UTC);
LocalDateTime utcDate = new LocalDateTime();
DateTimeZone utcTZ = DateTimeZone.forTimeZone(TimeZone.getTimeZone("ETC/UTC"));
DateTimeZone localTZ = DateTimeZone.forTimeZone(TimeZone.getTimeZone("America/Montreal"));
DateTimeFormatter fmt = DateTimeFormat.forPattern("yyyy-MM-dd'T'HH:mm:ss.SSSZ");
fmt.withZone(localTZ);
DateTime localDateTime = utcDate.toDateTime(localTZ);
DateTime utcDateTime = localDateTime.toDateTime(utcTZ);
Timestamp u = new Timestamp(utcDateTime.getMillis());
System.out.println("UTC Time: " + u);
LocalDateTime date = new LocalDateTime(u);
DateTime srcDateTime = date.toDateTime(utcTZ);
DateTime dstDateTime = srcDateTime.toDateTime(localTZ);
System.out.println("UTC+/- Time: " + dstDateTime.toString());
DateTime dateTimeInTargetTimezone = dstDateTime.withZone(localTZ);
System.out.println("Wall Time: " + dateTimeInTargetTimezone.toString("yyy-MM-dd HH:mm:ss"));
Now, when extracting the UTC time from the DB in a Timestamp object, we need
to display the time to the end user in a "Wall/Funeral Time", whatever you want to call it, in their TZ.
Output
UTC Time: 2015-05-15 20:03:47.561 "Good"
UTC+/- Time: 2015-05-15T20:03:47.561-04:00 "Good"
Wall Time: 2015-05-15 20:03:47 "No! No! No! Danger! We'll be late!"
What in the name! Do I have to do to get dstDateTime to equal the time I see on my wall (ie, 2015-05-15 4:03:47).
Update (2)
Got rid of Timestamp:
DateTimeZone utcTZ = DateTimeZone.forTimeZone(TimeZone.getTimeZone("ETC/UTC"));
DateTimeZone localTZ = DateTimeZone.forTimeZone(TimeZone.getTimeZone("America/Montreal"));
DateTimeFormatter fmt = DateTimeFormat.forPattern("yyy-MM-dd HH:mm:ss");
LocalDateTime utcDate = new LocalDateTime(utcTZ);
DateTime utcDateTime = utcDate.toDateTime(utcTZ);
System.out.println("UTC Time: " + utcDateTime);
DateTime dstDateTime = utcDateTime.toDateTime(localTZ);
System.out.println("Unformated Wall Time: " + dstDateTime);
System.out.println("Wall Time: " + dstDateTime.toString(fmt));
Output
UTC Time: 2015-05-20T14:09:28.469Z
Unformated Wall Time: 2015-05-20T10:09:28.469-04:00
Wall Time: 2015-05-20 10:09:28
Everything looks perfect however, when I try to right the UTZ date to the DB,
I need to convert to Timestamp (ie, new Timestamp(o.getOrderDate().getMillis())), and it obviously rights the local time to the DB, and not the UTC Zulu time that I need.
Thanks in Advance,
Nick.
#Nick
I'm not sure if I understood your question correctly but you can try this:
//sample input
String timestamp = "2015-05-15T03:28:49.523-04:00";
//format to parse
DateTimeFormatter dateTimeF = DateTimeFormat.forPattern("yyyy-MM-dd'T'HH:mm:ss.SSSZ");
//parse to local date time
LocalDateTime dateTime = dateTimeF.parseLocalDateTime(timestamp).minusHours(4);
//output here minus 4 hours
System.out.println(dateTime);
You can improve your implementation from my sample code above and make the offset hours more dynamic but so far this code provides the result as you mentioned in your example.
Goodluck!
Just use the DateTime.withZone method to change the timezone:
#Test
public void change_timezone() {
String input = "2015-05-15T03:28:49.523-04:00";
DateTimeZone targetTimeZone = DateTimeZone.forID("Europe/London");
DateTime dateTime = DateTime.parse(input);
DateTime dateTimeInTargetTimezone = dateTime.withZone(targetTimeZone);
assertThat(dateTimeInTargetTimezone.toString("yyy-MM-dd HH:mm:ss"),
equalTo("2015-05-15 08:28:49"));
}

JodaTime - how to get current time in UTC

I want to get the current time in UTC. What I do so far is following (just for testing purposes):
DateTime dt = new DateTime();
DateTimeZone tz = DateTimeZone.getDefault();
LocalDateTime nowLocal = new LocalDateTime();
DateTime nowUTC = nowLocal.toDateTime(DateTimeZone.UTC);
Date d1 = nowLocal.toDate();
Date d2 = nowUTC.toDate();
L.d("tz: " + tz.toString());
L.d("local: " + d1.toString());
L.d("utc: " + d2.toString());
d1 is my local time, that's fine
d2 is my local time + 1, but should be local time - 1...
My local time zone is UTC+1 (according to the debug output and the list here: https://www.joda.org/joda-time/timezones.html)...
How do I correctly convert from one time zone to another (inclusive the millisecond representation)?
EDIT
I need the date/milliseconds... It's NOT about displaying the time correctly....
EDIT 2
Now, with the help of a comment and an answer, I tried following:
DateTimeZone tz = DateTimeZone.getDefault();
DateTime nowLocal = new DateTime();
LocalDateTime nowUTC = nowLocal.withZone(DateTimeZone.UTC).toLocalDateTime();
DateTime nowUTC2 = nowLocal.withZone(DateTimeZone.UTC);
Date dLocal = nowLocal.toDate();
Date dUTC = nowUTC.toDate();
Date dUTC2 = nowUTC2.toDate();
L.d(Temp.class, "------------------------");
L.d(Temp.class, "tz : " + tz.toString());
L.d(Temp.class, "local : " + nowLocal + " | " + dLocal.toString());
L.d(Temp.class, "utc : " + nowUTC + " | " + dUTC.toString()); // <= WORKING SOLUTION
L.d(Temp.class, "utc2 : " + nowUTC2 + " | " + dUTC2.toString());
OUTPUT
tz : Europe/Belgrade
local : 2015-01-02T15:31:38.241+01:00 | Fri Jan 02 15:31:38 MEZ 2015
utc : 2015-01-02T14:31:38.241 | Fri Jan 02 14:31:38 MEZ 2015
utc2 : 2015-01-02T14:31:38.241Z | Fri Jan 02 15:31:38 MEZ 2015
What I wanted was, that the local date displays 15 o'clock and utc date displays 14 o'clock...
For now, this seems to work...
----- EDIT3 - Final solution -----
Hopefully, this is a good solution... I think, i respects all tipps i got...
DateTimeZone tz = DateTimeZone.getDefault();
DateTime nowUTC = new DateTime(DateTimeZone.UTC);
DateTime nowLocal = nowUTC.withZone(tz);
// This will generate DIFFERENT Dates!!! As I want it!
Date dLocal = nowLocal.toLocalDateTime().toDate();
Date dUTC = nowUTC.toLocalDateTime().toDate();
L.d("tz : " + tz.toString());
L.d("local : " + nowLocal + " | " + dLocal.toString());
L.d("utc : " + nowUTC + " | " + dUTC.toString());
Output:
tz : Europe/Belgrade
local : 2015-01-03T21:15:35.170+01:00 | Sat Jan 03 21:15:35 MEZ 2015
utc : 2015-01-03T20:15:35.170Z | Sat Jan 03 20:15:35 MEZ 2015
You're making it far more complicated than you need to:
DateTime dt = new DateTime(DateTimeZone.UTC);
No conversion required at all. If you find you actually need to convert, you can use withZone. I'd suggest you avoid going via LocalDateTime, however, as that way you can lose information due to time zone transitions (two different instants can have the same local time in the same time zone, because clocks go back and repeat local time.
Having said all of this, for the sake of testability I personally like using a Clock interface which allows me to get the current time (e.g. as an Instant). You can then use dependency injection to inject a real system clock when running in production, and a fake clock with a preset time for tests. Java 8's java.time package has this idea built into it, btw.
You can also use the static method now which makes it even more readable
DateTime.now(DateTimeZone.UTC)
Use this
DateTime.now().withZone(DateTimeZone.UTC)
and if you want to format, you can use
DateTime.now().withZone(DateTimeZone.UTC).toString("yyyyMMddHHmmss")
Please try to listen to Jon Skeets good advise and comments. Here an additional explanation. Your edit-2 contains a mistake:
DateTimeZone tz = DateTimeZone.getDefault();
DateTime nowLocal = new DateTime();
LocalDateTime nowUTC = nowLocal.withZone(DateTimeZone.UTC).toLocalDateTime();
DateTime nowUTC2 = nowLocal.withZone(DateTimeZone.UTC);
Date dLocal = nowLocal.toDate();
Date dUTC = nowUTC.toDate();
Date dUTC2 = nowUTC2.toDate();
If you call toDate() on an object nowUTC of type LocalDateTime then you can get surprises - see javadoc. Joda-Time claims to use the same fields in java.util.Date as in nowUTC. What does this mean? Let's analyze:
nowUTC.toString() produces 2015-01-02T14:31:38.241 That is without timezone (note the missing Z at the end), so it is just a plain local timestamp. By context, we know it was generated in UTC. In your next step however, you convert it to a java.util.Date using the mentioned method above. This method combines the local timestamp with the system timezone (Belgrade) PRESERVING the FIELDS, hence CHANGING the instant. So you have finally miscorrected your instant. And your second line is wrong.
If you just want
utc date displays 14 o'clock
then don't use the questionable and misleading conversion method Joda-Time offers. Use instead a dedicated formatter with the pattern "EEE MMM dd HH:mm:ss zzz yyyy" or similar (Joda-Time offers DateTimeFormatter). Set the UTC-offset on this formatter and print. Done. Abandon completely any call of java.util.Date.toString(). This way, you don't even need to do any dangerous conversion at all.
From here: http://www.joda.org/joda-time/userguide.html#Changing_TimeZone
// get current moment in default time zone
DateTime dt = new DateTime();
// translate to London local time
DateTime dtLondon = dt.withZone(DateTimeZone.forID("Europe/London"));
The resulting value dtLondon has the same absolute millisecond time, but a different set of field values.
You can substitute `Europe/London' for the timezone you want (UTC). See this list of proper time zone names.
SimpleDateFormat sdf = new SimpleDateFormat( "yyyy-MM-dd HH:mm:ss" );
// or SimpleDateFormat sdf = new SimpleDateFormat( "MM/dd/yyyy KK:mm:ss a Z" );
sdf.setTimeZone( TimeZone.getTimeZone( "UTC" ) );
System.out.println( sdf.format( new Date() )
);
Instead of System.out.println( sdf.format( new Date() ) put your local date
I fixed this with this converter
public class DateTimeConverter implements AttributeConverter<DateTime, Date> {
#Override
public Date convertToDatabaseColumn(DateTime attribute) {
return attribute == null ? null
: new Date(attribute
.withZone(DateTimeZone.UTC)
.withZoneRetainFields(DateTimeZone.getDefault())
.getMillis());
}
#Override
public DateTime convertToEntityAttribute(Date dbData) {
return dbData == null ? null
: new DateTime(dbData.getTime())
.withZoneRetainFields(DateTimeZone.UTC)
.withZone(DateTimeZone.getDefault());
}
}
Dates are stored as UTC and recovered with your current time zone

Java date displays previous day , month and totally different year

I am trying to display Date based on timezone.
If I change my system time zone to US pacific time zone, today's date is displayed correctly. If I want to display 2000-01-01 output shows as 12/31/1969.
Can you please let me know if I have to make any change in system settings or java settings?.
Below is the example code:
package timezoneexample;
import java.text.DateFormat;
import java.util.Date;
import java.util.TimeZone;
public class TimezoneExample {
public static void main(String args[]) {
DateFormat dateFormat = null;
String datePattern = null;
char dateSeperator = '/';
try {
datePattern = "MM/dd/yyyy";
if (datePattern.length() <= 0)
throw new java.util.MissingResourceException(
"Didn't find date format", "", "");
boolean hasSeperatorAlready = false;
for (int i = 0; i < datePattern.length(); i++)
if (!Character.isLetter(datePattern.charAt(i)))
if (hasSeperatorAlready)
throw new java.util.MissingResourceException(
"Unvalid date format", "", "");
else
dateSeperator = datePattern.charAt(i);
} catch (java.util.MissingResourceException mre) {
System.out.println(mre);
}
dateFormat = DateFormat.getDateInstance(DateFormat.MEDIUM);
if (datePattern.length() > 0
&& dateFormat instanceof java.text.SimpleDateFormat) {
java.text.SimpleDateFormat sdf = (java.text.SimpleDateFormat) dateFormat;
sdf.applyPattern(datePattern);
}
dateFormat.setTimeZone(java.util.TimeZone.getDefault());
// enter DOB
Date dob = new Date(2000 - 01 - 01);
Date today = new Date();
String timeZone = System.getProperties().getProperty("user.timezone");
TimeZone tZone = TimeZone.getTimeZone(timeZone);
System.out.println("Timezone : " + tZone);
dateFormat.setTimeZone(tZone);
System.out.println("Date Of Birth : " + dateFormat.format(dob));
System.out.println("Date in Displayed as per Timezone : "
+ dateFormat.format(today));
}
}
Output:
Timezone : sun.util.calendar.ZoneInfo[id="America/Los_Angeles",offset=-28800000,dstSavings=3600000,useDaylight=true,transitions=185,lastRule=java.util.SimpleTimeZone[id=America/Los_Angeles,offset=-28800000,dstSavings=3600000,useDaylight=true,startYear=0,startMode=3,startMonth=2,startDay=8,startDayOfWeek=1,startTime=7200000,startTimeMode=0,endMode=3,endMonth=10,endDay=1,endDayOfWeek=1,endTime=7200000,endTimeMode=0]]
Date Of Birth : 12/31/1969
Date in Displayed as per Timezone : 01/07/2015
Your error is here:
Date dob = new Date(2000 - 01 - 01);
This will be interpreted as:
Date dob = new Date(1998);
This will invoke the Date(long date) constructor, resulting in a date near 1970/01/01.
What you most probably want is:
Date dob = new Date(2000, 1, 1);
new Date(...) requires a long value, expressing the number of milliseconds since 1/1/1970. You're specifying 2000 - 1 - 1. This is NOT "year 2000, month 1 and day 1", it is a numeric expression equal to 1998 milliseconds.
To create a date based on year/month/day, use a Calendar:
Calendar c = Calendar.getInstance();
c.set(y, m-1 /* 0-based */, d); // e.g. c.set(2000, 0, 1);
return c.getTime();

Strange behaviour when comparing DateTime objects with JODA

Let me depict my scenario:
I have a running app in a server that is located in Dallas, Texas (I think it internally uses EDT timezone). In this server I need to get the time server, convert it to Europe/Madrid timezone and then check if the obtained date is within a Date Interval.
The weird thing is that I'm getting a response that suggests that the current server time once it is converted to Europe/Madrid timezone in BEFORE the lower date interval, which is very weird.
Here is how I'm doing this, getting the server time and convert it to Europe/Madrid timezone:
DateTimeZone timeZoneMadrid = DateTimeZone.forID( "Europe/Madrid" );
DateTimeFormatter formatter = DateTimeFormat.forPattern("YYYY-MM-dd HH:mm");
DateTime nowServer = new DateTime();
log.debug("Current server time is " + nowServer.toString(formatter));
DateTime nowServerSpanishTimeZone = nowServer.withZone(timeZoneMadrid);
log.debug("Current server time converted to Madrid Zone is " + nowServerSpanishTimeZone.toString(formatter));
Output:
Current server is 2014-10-06 06:12
Current server time converted to Madrid Zone is 2014-10-06 12:12
Now, I create the DateTime for the interval, start and end, based on the converted DateTime:
int year = serverTimeConverted.getYear();
int month = serverTimeConverted.getMonthOfYear();
int day = serverTimeConverted.getDayOfMonth();
this.setStartDate(new DateTime(year, month, day, 8, 0, 0, 0));
this.setEndDate(new DateTime(year, month, day, 21, 0, 0, 0));
As you can see, my interval goes from 08:00:00 to 21:00:00
Then I check if the server time converted is within the date range, this is very verbose because I added a lot of checking and output because of the strange behaviour...:
private boolean withinTimeRange(DateTime now, DateTime start, DateTime end){
DateTimeFormatter formatter = DateTimeFormat.forPattern("YYYYMMdd-HH:mm");
String currentDate = now.toString(formatter);
long nowTimeStamp = now.getMillis() / 1000;
long startTimeStamp = start.getMillis() / 1000;
long endTimeStamp = end.getMillis() / 1000;
log.debug("Checking if date " + currentDate + " is in the interval dates " + start.toString(formatter) + " and " + end.toString(formatter));
log.debug("Checking if UNIX timestamp " + nowTimeStamp + " is in the interval dates " + startTimeStamp + " and " + endTimeStamp);
if (!now.isBefore(start)){
log.debug("Current time " + currentDate + " is not before " + start.toString(formatter));
if (!now.isAfter(end)){
log.debug("Current time " + currentDate + " is not after " + end.toString(formatter));
return true;
}
else{
log.debug("Current time " + currentDate + " is after " + end.toString(formatter));
return false;
}
}
else{
log.debug("Current time " + currentDate + " is before " + start.toString(formatter));
return false;
}
}
Just call the method with the time server converted and the start and end dates and, for the previous output, where server time converted is 2014-10-06 12:12, I get this output from previous method:
Checking if date 20141006-12:12 is in the interval dates 20141006-08:00 and 20141006-21:00
Checking if UNIX timestamp 1412590332 is in the interval dates 1412596800 and 1412643600
Current time 20141006-12:12 is before 20141006-08:00
Current timeserver converted to Madrid TimeZone is not within time range, skipping iteration
As you can see the timestamp from the server time converted is before the start datetime.....how is this possible?
I think I'm doing something wrong when creating the DateTime start and end, I've tried creating them with .withTimeZone("Europe/Madrid"), but then I get even strangest behaviour...any clues?
Thanks!
UPDATE: based on previous SO question here, I modified my previous code and now it works:
DateTime now = new DateTime();
LocalDate today = now.toLocalDate();
LocalDate tomorrow = today.plusDays(1);
DateTimeZone timeZoneMadrid = DateTimeZone.forID( "Europe/Madrid" );
DateTime start = today.toDateTimeAtStartOfDay(timeZoneMadrid);
DateTime end = tomorrow.toDateTimeAtStartOfDay(timeZoneMadrid);
start = start.plusHours(8);
end = end.minusHours(4);
Interval interval = new Interval(start, end);
DateTimeFormatter formatter = DateTimeFormat.forPattern("YYYY-MM-dd HH:mm");
String currentDate = now.toString(formatter);
if (interval.contains(now)){
return true;
}
else{
return false;
}
Method DateTime::getMillis returns milliseconds independent of zone. This value is a constant.
Once created DateTime instance will return the same millis in any time zone.
final DateTime now = DateTime.now();
now.withZone(texas).getMillis() == now.withZone(madrid).getMillis(); // true
DateTime::isAfter and DateTime::isBefore methods compares millis returned by DateTime::getMillis method.
So this value is also zone independent.
But printing DateTime with DateTimeFormatter is zone dependent. It will print different hours/minutes in in different time zones.
So, if you want compare dates zone independently, then your result is correct.
Example:
- Precondition:
DateTimeZone usZone = DateTimeZone.forID("US/Eastern");
DateTimeZone spZone = DateTimeZone.forID("Europe/Madrid");
DateTimeZone.setDefault(usZone);
Your code works in next way:
DateTime serverDate = new DateTime(2014, 10, 6, 6, 12); // US zone
DateTime dateInMadrid = serverDate.withZone(spZone); // zone is Madrid, but .getMillis() will return the same value
DateTime startDate = new DateTime(2014, 10, 6, 8, 0); // US zone
// startDate = startDate.withZone(spZone) - this will not change the result
DateTime endDate = new DateTime(2014, 10, 6, 21, 0); // US zone
// endDate = endDate.withZone(spZone) - this will also not change the result
System.out.println(dateInMadrid .isAfter(startDate) && dateInMadrid .isBefore(endDate));
// false - it is correct. because all dates were created in US zone
Correct way: you should create start and end dates in Madrid zone
DateTime serverDate = new DateTime(2014, 10, 6, 6, 12);
DateTime startDateMadrid = new DateTime(2014, 10, 6, 8, 0, spZone); // Madrid zone is used in constructor!
DateTime endDateMadrid = new DateTime(2014, 10, 6, 21, 0, spZone); // Madrid zone is used in constructor!
System.out.println(serverDate.isAfter(startDateMadrid) && serverDate.isBefore(endDateMadrid));
// true

How to compare item of set collection to current Date?

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.

Categories

Resources