Dates comparison in Java - java

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.

Related

How to convert util.Date to time.LocalDate correctly for dates before 1893

I googled for a while and the most commonly used method seems to be
date.toInstant().atZone(ZoneId.systemDefault()).toLocalDate();
However, this method seems to fail for dates before 1893-04-01
The following test fails on my machine with an outcome of 1893-03-31 instead of 1893-04-01:
#Test
public void testBeforeApril1893() throws ParseException {
Date date = new SimpleDateFormat("yyyy-MM-dd").parse("1893-04-01");
System.out.println(date);
LocalDate localDate2 = date.toInstant().atZone(ZoneId.systemDefault()).toLocalDate();
System.out.println(localDate2);
assertEquals(1893, localDate2.getYear());
assertEquals(4, localDate2.getMonth().getValue());
assertEquals(1, localDate2.getDayOfMonth());
}
The System.out.prinlns are for me to double check the created dates. I see the following output:
Sun Apr 02 00:00:00 CET 1893
1893-04-02
Sat Apr 01 00:00:00 CET 1893
1893-03-31
For 1400-04-01 I even get an output of 1400-04-09.
Is there any method to convert dates before 1893-04 correctly to LocalDate?
As some helpfully pointed out, the reason for this shift is explained in this question. However, I don't see how I can deduce a correct conversion based on this knowledge.
If you're just parsing a String input, it's straighforward:
LocalDate d1 = LocalDate.parse("1893-04-01");
System.out.println(d1); // 1893-04-01
LocalDate d2 = LocalDate.parse("1400-04-01");
System.out.println(d2); // 1400-04-01
The output is:
1893-04-01
1400-04-01
But if you have a java.util.Date object and need to convert it, it's a little bit more complicated.
A java.util.Date contains the number of milliseconds from unix epoch (1970-01-01T00:00Z). So you can say "it's in UTC", but when you print it, the value is "converted" to the system's default timezone (in your case, it's CET). And SimpleDateFormat also uses the default timezone internally (in obscure ways that I must admit I don't fully understand).
In your example, the millis value of -2422054800000 is equivalent to the UTC instant 1893-03-31T23:00:00Z. Checking this value in Europe/Berlin timezone:
System.out.println(Instant.ofEpochMilli(-2422054800000L).atZone(ZoneId.of("Europe/Berlin")));
The output is:
1893-03-31T23:53:28+00:53:28[Europe/Berlin]
Yes, it's very strange, but all places used strange offsets before 1900 - each city had its own local time, before UTC standard took place. That explains why you get 1893-03-31. The Date object prints April 1st probably because the old API (java.util.TimeZone) doesn't have all the offsets history, so it assumes it's +01:00.
One alternative to make this work is to always use UTC as the timezone:
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
sdf.setTimeZone(TimeZone.getTimeZone("UTC")); // set UTC to the format
Date date = sdf.parse("1893-04-01");
LocalDate d = date.toInstant().atZone(ZoneOffset.UTC).toLocalDate();
System.out.println(d); // 1893-04-01
This will get the correct local date: 1893-04-01.
But for dates before 1582-10-15, the code above doesn't work. That's the date when the Gregorian Calendar was introduced. Before it, the Julian Calendar was used, and dates before it need an adjustment.
I could do it with the ThreeTen Extra project (an extension of java.time classes, created by the same guy BTW). In the org.threeten.extra.chrono package there are the JulianChronology and JulianDate classes:
// using the same SimpleDateFormat as above (with UTC set)
date = sdf.parse("1400-04-01");
// get julian date from date
JulianDate julianDate = JulianChronology.INSTANCE.date(date.toInstant().atZone(ZoneOffset.UTC));
System.out.println(julianDate); // Julian AD 1400-04-01
The output will be:
Julian AD 1400-04-01
Now we need to convert the JulianDate to a LocalDate. If I do LocalDate.from(julianDate) it converts to Gregorian calendar (and the result is 1400-04-10).
But if you want to create a LocalDate with exactly 1400-04-01, you'll have to do this:
LocalDate converted = LocalDate.of(julianDate.get(ChronoField.YEAR_OF_ERA),
julianDate.get(ChronoField.MONTH_OF_YEAR),
julianDate.get(ChronoField.DAY_OF_MONTH));
System.out.println(converted); // 1400-04-01
The output will be:
1400-04-01
Just be aware that dates before 1582-10-15 have this adjustment and SimpleDateFormat can't handle these cases properly. If you need to work just with 1400-04-01 (year/month/day values), use a LocalDate. But if you need to convert it to a java.util.Date, be aware that it might not be the same date (due to Gregorian/Julian adjustments).
If you don't want to add another dependency, you can also do all the math by hand. I've adapted the code from ThreeTen, but IMO the ideal is to use the API itself (as it can cover corner cases and other things I'm probably missing by just copying a piece of code):
// auxiliary method
public LocalDate ofYearDay(int prolepticYear, int dayOfYear) {
boolean leap = (prolepticYear % 4) == 0;
if (dayOfYear == 366 && leap == false) {
throw new DateTimeException("Invalid date 'DayOfYear 366' as '" + prolepticYear + "' is not a leap year");
}
Month moy = Month.of((dayOfYear - 1) / 31 + 1);
int monthEnd = moy.firstDayOfYear(leap) + moy.length(leap) - 1;
if (dayOfYear > monthEnd) {
moy = moy.plus(1);
}
int dom = dayOfYear - moy.firstDayOfYear(leap) + 1;
return LocalDate.of(prolepticYear, moy.getValue(), dom);
}
// sdf with UTC set, as above
Date date = sdf.parse("1400-04-01");
ZonedDateTime z = date.toInstant().atZone(ZoneOffset.UTC);
LocalDate d;
// difference between the ISO and Julian epoch day count
long julianToIso = 719164;
int daysPerCicle = (365 * 4) + 1;
long julianEpochDay = z.toLocalDate().toEpochDay() + julianToIso;
long cycle = Math.floorDiv(julianEpochDay, daysPerCicle);
long daysInCycle = Math.floorMod(julianEpochDay, daysPerCicle);
if (daysInCycle == daysPerCicle - 1) {
int year = (int) ((cycle * 4 + 3) + 1);
d = ofYearDay(year, 366);
} else {
int year = (int) ((cycle * 4 + daysInCycle / 365) + 1);
int doy = (int) ((daysInCycle % 365) + 1);
d = ofYearDay(year, doy);
}
System.out.println(d); // 1400-04-01
The output will be:
1400-04-01
Just reminding that all this math is not needed for dates after 1582-10-15.
Anyway, if you have an input String and want to parse it, don't use SimpleDateFormat - you can use LocalDate.parse() instead. Or LocalDate.of(year, month, day) if you already know the values.
But converting these local dates from/to a java.util.Date is more complicated, because Date represents the full timestamp millis and dates can vary according to the calendar system in use.
Seems to be a known bug that won't get fixed: https://bugs.openjdk.java.net/browse/JDK-8061577
After a lot of research I gave up with every simple API method and just convert it by hand. You could wrap the date in a sql.Date and call toLocalDate() or you just use the same deprecated methods as sql.Date does.
Without deprecated methods you need to convert your util.Date to Calendar and get the fields one by one:
Calendar calendar = Calendar.getInstance();
calendar.setTime(value);
return LocalDate.of(calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH) + 1,
calendar.get(Calendar.DAY_OF_MONTH));
If you futher want to have a two digit year conversion like in SimpleDateFormat (convert the date in range of now - 80 years till now + 19 years) you could use this implementation:
Calendar calendar = Calendar.getInstance();
calendar.setTime(value);
int year = calendar.get(Calendar.YEAR);
if (year <= 99) {
LocalDate pivotLocalDate = LocalDate.now().minusYears(80);
int pivotYearOfCentury = pivotLocalDate.getYear() % 100;
int pivotCentury = pivotLocalDate.minusYears(pivotYearOfCentury).getYear();
if (year < pivotYearOfCentury) {
year += 100;
}
year += pivotCentury;
}
return LocalDate.of(year, calendar.get(Calendar.MONTH) + 1, calendar.get(Calendar.DAY_OF_MONTH));
Conclusion: it is realy ugly and I can't believe that there isn't any simple API!
This code works for me:
#Test
public void oldDate() throws ParseException {
Date date = new SimpleDateFormat("yyyy-MM-dd").parse("1893-04-01");
assertEquals("1893-04-01", String.format("%tF", date));
}

validation to check date formatting is not working as expected

I have following code which checks for the valid format date
private void validateDate(String date){
try {
String validDate = "MM/dd/yyyy";
SimpleDateFormat format = new SimpleDateFormat(validDate);
format.setLenient(false);
Date theDate = new Date();
theDate = format.parse(date);
}
catch (Exception e) {
}
}
I am passing the date value as 06/25/20014. In this year format is wrong and I was expecting that it will throw exception and will go inside catch, but it never happens and it successfully passes the code format.parse(date); due to which my application is not throwing error.
I also debugged the line format.parse(date); and it returns "Fri Jul 31 00:00:00 MST 20015". I am not sure why that line is not throwing any exception.
Thanks for your help!!
In the standard date formats for SimpleDateFormat, the number 'y' 's doesn't necessarily correspond to the number of digits (it isn't a regex). One or two y's is an indicator for a 2 digit year (15, 98, etc.) and 3 or more y's is an indicator for the full year.
If this line did throw an exception, then your program would stop working after year 9999, which is not usually what you want. Sure, you do not expect your program to last this long, but people did not expect to last up to y2k either; so Java's choice not to block at any date seems reasonable.
If you want to check the year is between 1 and 9999, you can just write a if: (see related question I want to get Year, Month, Day, etc from Java Date to compare with Gregorian Calendar date in Java. Is this possible?)
Calendar cal = Calendar.getInstance();
cal.setTime(date);
if (cal.get(Calendar.YEAR) > 9999)
throw new RuntimeException("Blah");
This is actually documented behaviour (at least for the Gregorian calendar, which I assume you will be using unless you explicitely set it to a different calendar):
Year: If the formatter's Calendar is the Gregorian calendar, the
following rules are applied.
For formatting, if the number of pattern
letters is 2, the year is truncated to 2 digits; otherwise it is
interpreted as a number. For parsing, if the number of pattern letters
is more than 2, the year is interpreted literally, regardless of the
number of digits.
And yes, 20015 will probably be a valid year some day ;) If you want to check for exactly 4 digits, you might want to consider using a regular expression matching before parsing.
I can see that the provided date is valid (although 18k years ahead)
public static void validateDate(String date){
try {
String validDate = "MM/dd/yyyy";
SimpleDateFormat format = new SimpleDateFormat(validDate);
format.setLenient(false);
Date theDate = format.parse(date);
Calendar c = new GregorianCalendar();
c.setTime(theDate);
int year = c.get(Calendar.YEAR);
int month = c.get(Calendar.MONTH);
int day = c.get(Calendar.DAY_OF_MONTH);
int pos = c.get(Calendar.DAY_OF_WEEK);
if (Calendar.WEDNESDAY == pos)
System.out.print("day is Wednesday on " + year + "/" + (month+1) + "/" + day);
}
catch (Exception e) {
System.out.print("Inside exception block " + e);
}
}
prints: day is Wednesday on 20014/6/25
If you need some year validation you can add additional check
if (year > MAX_YEAR) {
// add error here
}
Here is DEMO

Convert month name to Date range

I need to convert Monthname + Year to a valid date range. It needs to work with leap years etc.
Examples
getDateRange("Feb",2015)
should find the range 2015-02-01 -- 2015-02-28
While
getDateRange("Feb",2016)
should find the range 2016-02-01 -- 2016-02-29
In Java 8, you can do that using TemporalAdjusters,
LocalDate firstDate= date.with(TemporalAdjusters.firstDayOfMonth());
LocalDate lastDate= date.with(TemporalAdjusters.lastDayOfMonth());
If you have only year and month, it is better to use YearMonth. From YearMonth you can easily get length of that month.
YearMonth ym= YearMonth.of(2015, Month.FEBRUARY);
int monthLen= ym.lengthOfMonth();
Java 8 made Date-Time operations very simple.
For Java 7 and below you could get away with something like this;
void getDate(String month, int year) throws ParseException {
Date start = null, end = null;
//init month and year
SimpleDateFormat sdf = new SimpleDateFormat("MMM");
Date parse = sdf.parse(month);
Calendar instance = Calendar.getInstance();
instance.setTime(parse);
instance.set(Calendar.YEAR, year);
//start is default first day of month
start = instance.getTime();
//calculate end
instance.add(Calendar.MONTH, 1);
instance.add(Calendar.DAY_OF_MONTH, -1);
end = instance.getTime();
System.out.println(start + " " + end);
}
The output would be for "Feb", 2015:
Sun Feb 01 00:00:00 EET 2015
Sat Feb 28 00:00:00 EET 2015
Java 7 solution with default Java tools:
public static void getDateRange(String shortMonth, int year) throws ParseException {
SimpleDateFormat format = new SimpleDateFormat("MMM yyyy", Locale.ENGLISH);
// the parsed date will be the first day of the given month and year
Date startDate = format.parse(shortMonth + " " + year);
Calendar calendar = Calendar.getInstance();
calendar.setTime(startDate);
// set calendar to the last day of this given month
calendar.set( Calendar.DATE, calendar.getActualMaximum(Calendar.DATE));
// and get a Date object
Date endDate = calendar.getTime();
// do whatever you need to do with your dates, return them in a Pair or print out
System.out.println(startDate);
System.out.println(endDate);
}
Try (untested):
public List<LocalDate> getDateRange(YearMonth yearMonth){
List<LocalDate> dateRange = new ArrayList<>();
IntStream.of(yearMonth.lengthOfMonth()).foreach(day -> dateRange.add(yearMonth.at(day));
return dateRange
}
Java 8 provides new date API as Masud mentioned.
However if you are not working under a Java 8 environment, then lamma date is a good option.
// assuming you know the year and month already. Because every month starts from 1, there should be any problem to create
Date fromDt = new Date(2014, 2, 1);
// build a list containing each date from 2014-02-01 to 2014-02-28
List<Date> dates = Dates.from(fromDt).to(fromDt.lastDayOfMonth()).build();

Date.compareTo(Date) not working

I am writing an app scenario, where need to match between two date if there are same or not and that I am trying to achieve using Date.compareTo(). But it never return 0 as API said for equal date.
I am getting these dates from Caledar.getTime() but it never
I checked with print to both date object and even they are returning same string.
Sat Nov 15 14:17:41 GMT+05:30 2014, Sat Nov 15 14:17:41 GMT+05:30 2014
Any suggestion, how to check date object if they are equal or not.
I think you forgot to check if the dates milliseconds are the same.
This is the source code of the compareTo method.
public int compareTo(Date anotherDate) {
long thisTime = getMillisOf(this);
long anotherTime = getMillisOf(anotherDate);
return (thisTime<anotherTime ? -1 : (thisTime==anotherTime ? 0 : 1));
}
As you can see this method compares two dates using milliseconds as "time step".
Code for old API:
This code checks if two days are the same. (Without hours, minutes, seconds and milliseconds)
Date date1; //Your initial date
Date date2; //Your initial second date
//Remove hours, minutes, seconds and milliseconds by creating new "clean" Date objects
Date compare1 = new Date(date1.getYear(), date1.getMonth(), date1.getDay());
Date compare2 = new Date(date2.getYear(), date2.getMonth(), date2.getDay());
if(compare1.compareTo(compare2) == 0){
}
But I suggest you don't use Date for this task. Because the getYear, getMonth etc. methods are deprecated I suggest you take a look at newer API's like GregorianCalendar and Calendar
Code for new API
This code checks if two days are the same including hours and minutes. But without seconds and milliseconds.
Date date1;
Date date2;
Calendar compareCalendar1 = Calendar.getInstance();
Calendar compareCalendar2 = Calendar.getInstance();
compareCalendar1.setTime(date1);
compareCalendar2.setTime(date2);
//Set for both calendars the seconds and milliseconds to 0
compareCalendar1.set(Calendar.MILLISECOND, 0);
compareCalendar1.set(Calendar.SECOND, 0);
compareCalendar2.set(Calendar.MILLISECOND, 0);
compareCalendar2.set(Calendar.SECOND, 0);
if(compareCalendar1.compareTo(compareCalendar2) == 0){
}
Try to understand compare scenario :
Date date1 = Calendar.getInstance().getTime();
Date date2 = Calendar.getInstance().getTime();
date1.compareTo(date2) >> -1
AND
Date date3 = Calendar.getInstance().getTime();
Date date4 = date3;
date3.compareTo(date4) >> 0

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