How to check today date is first day of the current month - java

How to find out if the today date is the first day of the current month.
Say, today is 24/05/2015 but it is not first day of the month.
what is the best way to get the output.

Extract the "day" part and compare it to 1:
if (Calendar.getInstance().get(Calendar.DAY_OF_MONTH) == 1) {
System.out.println ("Today is the first day of the month");
}

Check if it is say 1 of the month, like so:
Calendar calendar = Calendar.getInstance();
int day = calendar.get(Calendar.DAY_OF_MONTH);
if (day == 1) {
// first day of the month.
}

Using joda:
boolean isFirstDay = new DateTime(dateObject).getDayOfMonth() == 1;
if(isFirstDay) {
// do whatever
} else {
// whatever
}

Related

LocalDateTime Java - Get same day of week for next month

I have a date and a time of a month, for example 31/01/2020 at 14:00:00, this is the last friday of January. How can I get the date for the last Friday of Feb, March, etc.? It should be dynamic because any date can come in, like the second Tuesday of any month and so on.
I am trying with the following with no luck:
LocalDateTime startTime = LocalDateTime.of(2020, 1, 31, 14, 0, 0);
final Calendar calendar = Calendar.getInstance();
calendar.set(startTime.getYear(), startTime.getMonthValue() - 1, startTime.getDayOfMonth(), startTime.getHour(), startTime.getMinute(), startTime.getSecond());
int ordinal = calendar.get(Calendar.WEEK_OF_MONTH);
startTime = startTime.plusMonths(1).with(TemporalAdjusters.dayOfWeekInMonth(ordinal, startTime.getDayOfWeek();
System.out.println(startTime);
it's printing 06/03/2020 (six of march) at 14:00:00 which is wrong and should be 28/02/2020
What am I missing?
Thanks!
As mentioned before, there is some ambiguity in which day of the week of the month you mean, that is, whether you mean the nth day of week or the last nth day of week of the month.
One such example is Monday, February 24th, 2020. It is the fourth and last Monday of February 2020. If you are going to try to determine this for March 2020, which Monday would you pick? The fourth Monday is 23 March, but the last Monday is 30 March.
So apparently, you'll need to distinguish between whether you count forward or backward.
You could, for instance, create a class which represents a certain day of week in a month. This holds three fields: a day-of-week, a position, and whether the position is backwards or not. E.g.
"The second Monday of the month" would have
dayOfWeek = DayOfWeek.MONDAY
position = 2
backwards = false
and
"The last Thursday of the month" would have
dayOfWeek = DayOfWeek.THURSDAY
position = 1
backwards = true
public class WeekdayInMonth {
private final boolean backwards;
private final DayOfWeek dayOfWeek;
private final int position;
private WeekdayInMonth(DayOfWeek dayOfWeek, int position, boolean backwards) {
if (position < 1 || position > 5) {
throw new DateTimeException("Position in month must be between 1 and 5 inclusive");
}
this.dayOfWeek = dayOfWeek;
this.position = position;
this.backwards = backwards;
}
}
We could add factory methods to create WeekdayInMonths from LocalDates:
public static WeekdayInMonth of(LocalDate date) {
int positionInMonth = (date.getDayOfMonth() - 1) / 7 + 1;
return new WeekdayInMonth(date.getDayOfWeek(), positionInMonth, false);
}
private static WeekdayInMonth ofReversing(LocalDate date) {
int lastDayOfMonth = date.with(TemporalAdjusters.lastDayOfMonth()).getDayOfMonth();
int positionInMonth = (lastDayOfMonth - date.getDayOfMonth()) / 7 + 1;
return new WeekdayInMonth(date.getDayOfWeek(), positionInMonth, true);
}
At last, we add a method to get a LocalDate from a YearMonth adjusted to the WeekdayInMonth.
public LocalDate toLocalDate(YearMonth yearMonth) {
// Get a temporal adjuster to adjust a LocalDate to match a day-of-the-week
TemporalAdjuster adjuster = this.backwards ? TemporalAdjusters.lastInMonth(this.dayOfWeek) : TemporalAdjusters.firstInMonth(this.dayOfWeek);
int weeks = this.position - 1;
LocalDate date = yearMonth.atDay(1)
.with(adjuster)
.plusWeeks(this.backwards ? 0 - weeks : weeks);
if (!Objects.equals(yearMonth, YearMonth.from(date))) {
throw new DateTimeException(String.format("%s #%s in %s does not exist", this.dayOfWeek, this.position, yearMonth));
}
return date;
}
Working example
Here a working example at Ideone.
Addendum
I am getting errors like this if the initial date is Jan 1 2020: java.time.DateTimeException: FRIDAY #5 in 2020-02 does not exist. How could I get the previous weekday in case this happens? In this case, how would I get the previous Friday?
Well, then you need to adjust your LocalDate so that it falls within the specified yearmonth. Since every month has at least four day-of-the-weeks and no more than five of them, the difference is never more than a week. We could, after removing the throw new DateTimeException line, simply adjust the returned LocalDate using plusWeeks.
I've forked the abovementioned example and added the toAdjustingLocalDate method.
This solution is kind of complicated but this is because "last of" or "third in" etc aren't always well defined and might not even exists under some conditions. So here is a solution that looks at the initial date and depending of the day of the month it either performs calculations from the start of the month, calculating forward, or the end of the month, calculating backwards.
From my testing it seems to generate the right results and I am sure some code refactoring could be done as well to improve the code but I leave that for the reader.
public static LocalDateTime nextWithSameDayOfMonth(LocalDateTime indate) {
if (indate.getDayOfMonth() < 15) {
return getForStartOfMonth(indate);
}
return getForEndOfMonth(indate);
}
private static LocalDateTime getForEndOfMonth(LocalDateTime indate) {
DayOfWeek dayOfWeek = indate.getDayOfWeek();
LocalDateTime workDate = indate.with(TemporalAdjusters.lastDayOfMonth());
int count = 0;
while (workDate.isAfter(indate)) {
count++;
workDate = workDate.minusWeeks(1);
}
LocalDateTime nextDate = indate.plusMonths(1).with(TemporalAdjusters.lastDayOfMonth());
while (nextDate.getDayOfWeek() != dayOfWeek) {
nextDate = nextDate.minusDays(1);
}
return count == 0 ? nextDate : nextDate.minusWeeks(count - 1);
}
private static LocalDateTime getForStartOfMonth(LocalDateTime indate) {
DayOfWeek dayOfWeek = indate.getDayOfWeek();
LocalDateTime workDate = indate.with(TemporalAdjusters.firstDayOfMonth());
int count = 0;
while (workDate.isBefore(indate)) {
count++;
workDate = workDate.plusWeeks(1);
}
LocalDateTime nextDate = indate.plusMonths(1).with(TemporalAdjusters.firstDayOfMonth());
while (nextDate.getDayOfWeek() != dayOfWeek) {
nextDate = nextDate.plusDays(1);
}
return count == 0 ? nextDate : nextDate.plusWeeks(count - 1);
}
Could you check if the function work for you?
public class FindSameDayNextMonth {
public static void main(String[] args) {
System.out.println("Next month of 'today' is " + FindSameDayNextMonth.getSameDayNextMonth());
}
public static Date getSameDayNextMonth() {
LocalDateTime dt = LocalDateTime.now();
Calendar c = Calendar.getInstance();
c.set(Calendar.MONTH, dt.getMonthValue()-1);
c.set(Calendar.DAY_OF_MONTH, dt.getDayOfMonth());
c.add(Calendar.MONTH, 1);
return c.getTime();
}
}
The output is
Next month of today is Mon Sep 23 07:18:09 CDT 2019

last working day of previous month with LocalDate

public static String getLastWorkingDayOfPreviousMonth() {
LocalDate lastDayOfCurrentMonth = LocalDate.now().with(TemporalAdjusters.lastDayOfMonth());
LocalDate lastWorkingDayOfMonth;
switch (DayOfWeek.of(lastDayOfCurrentMonth.get(ChronoField.DAY_OF_WEEK))) {
case SATURDAY:
lastWorkingDayOfMonth = lastDayOfCurrentMonth.minusMonths(1);
break;
case SUNDAY:
lastWorkingDayOfMonth = lastDayOfCurrentMonth.minusMonths(2);
break;
default:
lastWorkingDayOfMonth = lastDayOfCurrentMonth;
}
return getFormattedDate(lastWorkingDayOfMonth);
}
The above gives last working day of the current month. How can I get the last working day of the Previous month adjusting the above?
Another alternative is to use a java.time.YearMonth to get the previous month. Then you get the last day of this month and adjust to previous Friday if it's in a weekend:
LocalDate lastDayPreviousMonth = YearMonth
// current year/month
.now()
// previous month
.minusMonths(1)
// last day of month
.atEndOfMonth();
DayOfWeek dayOfWeek = lastDayPreviousMonth.getDayOfWeek();
// check if it's weekend
if (dayOfWeek == DayOfWeek.SATURDAY || dayOfWeek == DayOfWeek.SUNDAY) {
// adjust to previous friday
lastDayPreviousMonth = lastDayPreviousMonth.with(TemporalAdjusters.previous(DayOfWeek.FRIDAY));
}
Running this code today (October 2nd 2017), it gives lastDayPreviousMonth equals to 2017-09-29.
PS: You're using minusMonths in LocalDate instances, which wont' always work like you want. Example, if I have a date in February 2017:
// Feb 15th 2017
LocalDate d = LocalDate.of(2017, 2, 15);
// adjust to last day of month (2017-02-28)
d = d.with(TemporalAdjusters.lastDayOfMonth());
System.out.println(d.minusMonths(1)); // 2017-01-28
The last day of February 2017 is 28th, and when calling minusMonths(1), you get the same day (28th) at the previous month (January), which is not what you want (the last working day in January 2017 is 31st).
Using YearMonth avoids this, because this class handles just the month and year, ignoring the day (so the minusMonths doesn't suffer such effects). So you can easily go to the desired month, and then you can correctly get the last day using the atEndOfMonth() method.
Sometimes, the simple approach is better than a clever approach:
LocalDate lastWorkingDayOfMonth = LocalDate.now().withDayOfMonth(1);
do {
lastWorkingDayOfMonth = lastWorkingDayOfMonth.minusDays(1);
} while (lastWorkingDayOfMonth.getDayOfWeek() == DayOfWeek.SATURDAY ||
lastWorkingDayOfMonth.getDayOfWeek() == DayOfWeek.SUNDAY);
You can change your switch statement with the following code:
public static String getLastWorkingDayOfPreviousMonth() {
LocalDate lastDayOfCurrentMonth = LocalDate.now().with(TemporalAdjusters.lastDayOfMonth());
LocalDate lastWorkingDayOfMonth;
switch (lastDayOfCurrentMonth.minusMonths(1).getDayOfWeek()) {
case SATURDAY:
lastWorkingDayOfMonth = lastDayOfCurrentMonth.minusMonths(1).minusDays(1); // Here assgining second last day from previous month.
break;
case SUNDAY:
lastWorkingDayOfMonth = lastDayOfCurrentMonth.minusMonths(1).minusDays(2); // Here assgining third last day from previous month.
break;
default:
lastWorkingDayOfMonth = lastDayOfCurrentMonth.minusMonths(1); // Here assgining last day from previous month.
}
return lastWorkingDayOfMonth.toString();
}
Here, in this case I am calculating the last day of previous month (you can change the months before by changing the integer value in method minusMonths()'s parameter) with the weekends and in case of Weekends the Working day is changed accordingly.
tl;dr
LocalDate.now()
.withDayOfMonth( 1 )
.with(
org.threeten.extra.Temporals.previousWorkingDay()
)
previousWorkingDay
The ThreeTen-Extra project provides TemporalAdjuster implementations for finding the next/previous weekday (non-Saturday/Sunday).
The last day of the previous month may be the target, a weekday. So our strategy is to get the first day of this month, the look back to get first previous working day.
ZoneId z = ZoneId.of( "America/Montreal" ) ;
LocalDate today = LocalDate.now( z );
LocalDate firstOfMonth = today.withDayOfMonth( 1 ) ;
LocalDate lastWorkingDayOfPreviousMonth = firstOfMonth.with( org.threeten.extra.Temporals.previousWorkingDay() ) ;
More simple and easy way without looping.
public static String getLastWorkingDayOfPreviousMonth() {
LocalDate localDate = LocalDate.now().minusMonths(1).with(TemporalAdjusters.lastDayOfMonth());
if (localDate.getDayOfWeek().getValue() > 5)
localDate = localDate.minusDays(localDate.getDayOfWeek().getValue() - 5);
return getFormattedDate(localDate);
}
You can replace LocalDate.now().with(TemporalAdjusters.lastDayOfMonth())
in your code to LocalDate.now().minusMonth(1).with(TemporalAdjusters.lastDayOfMonth()) to get the last day of the previous month and after that keep on with the same logic to find the last working day of the month.

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.

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!!

Android: compare calendar dates

In my app I´m saving when I last updated some data from my server.
Therefore I used:
long time = Calendar.getInstance().getTimeInMillis();
Now I want that the data is updated twice a year at 03.03 and 08.08.
How can I check wheater one of these two date boarders were crossed since last update?
Change them to time in mseconds and compare:
Calendar c = Calendar.getInstance();
c.set(Calendar.MONTH, Calendar.MARCH);
c.set(Calendar.DAY_OF_MONTH, 3);
long time2= c.getTimeInMillis();
c.set(Calendar.MONTH, Calendar.AUGUST);
c.set(Calendar.DAY_OF_MONTH, 8);
long time3= c.getTimeInMillis();
if(time>time2){
//Logic
if(time>time3){
//Logic
}
}
There is something very important which took me a while to figure it out and can be very helpful to people out there, if you are looking for an answer to any of the following questions this is for you:
Why is my date not showing correctly?
Why even when I set the time manually it is not showing right?
Why is the month and the year showing one day less than the one that I set?
For some reason Java sorts the months values like an array, what I mean is that for Java January is 0 and DECEMBER is 11. Same happens for the year, if you set December as month 12 and year as 2012, and then try to do a "system.out.println" of the month and the year, it will show my month as January and the year as 2013!!
so what should you do?
Calendar cal = new GregorianCalendar();
cal.set(2012, 11, 26); // the date I want to input is 26/12/2012 (for Java, 11 is December!)
NOW WHAT IS THE CORRECT WAY TO GET THAT DATE TO SEE IT ON THE SCREEN?
if you try to "system.out.println of yourCalendar.DATE, yourCalendar.MONTH and yourCalendar.YEAR," THAT WILL NOT SHOW YOU THE RIGHT DATE!!!!
If you want to display the dates you need to do the following:
System.out.println (calact.get (calact.DATE));
// displays day
System.out.println (calact.get (calact.MONTH)+1);
//add 1 remember it saves values from 0-11
System.out.println (calact.get (calact.YEAR));
// displays year
NOW IF YOU ARE HANDLING STRINGS THAT REPRESENT DATES, OR....
IF YOU NEED TO COMPARE DATES BETWEEN RANGES , LET'S SAY YOU NEED TO KNOW IF DATE "A" WILL TAKE PLACE WITHIN THE NEXT 10 DAYS....THIS....IS.....FOR....YOU!!
In my case I was working with a string that had format "15/07/2012", I needed to know if that date would take place within the next 10 days, therefore I had to do the following:
1 get that string date and transform it into a calendar ( StringTokenizer was used here )
this is very simple
StringTokenizer tokens=new StringTokenizer(myDateAsString, "/");
do nextToken and before returning the day, parse it as integer and return it.
Remember for month before returning substract 1.
I will post the code for the first you create the other two:
public int getMeD(String fecha){
int miDia = 0;
String tmd = "0";
StringTokenizer tokens=new StringTokenizer(fecha, "/");
tmd = tokens.nextToken();
miDia = Integer.parseInt(tmd);
return miDia;
}
2 THEN YOU CREATE THE CALENDAR
Calendar cal = new GregorianCalendar(); // calendar
String myDateAsString= "15/07/2012"; // my Date As String
int MYcald = getMeD(myDateAsString); // returns integer
int MYcalm = getMeM(myDateAsString); // returns integer
int MYcaly = getMeY(myDateAsString); // returns integer
cal.set(MYcaly, MYcalm, MYcald);
3 get my current date (TODAY)
Calendar curr = new GregorianCalendar(); // current cal
calact.setTimeInMillis(System.currentTimeMillis());
4 create temporal calendar to go into the future 10 days
Calendar caltemp = new GregorianCalendar(); // temp cal
caltemp.setTimeInMillis(System.currentTimeMillis());
caltemp.add(calact.DAY_OF_MONTH, 10); // we move into the future
5 compare among all 3 calendars
here basically you ask if the date that I was given is for sure taking place in the future AND (&&) IF the given date is also less than the future date which had 10 days more, then please show me "EVENT WILL TAKE PLACE FOR SURE WITHIN THE NEXT 10 DAYS!!" OTHERWISE SHOW ME:
"EVENT WILL NOT TAKE PLACE WITHIN THE NEXT 10 DAYS".
if((cal.getTimeInMillis() > curr.getTimeInMillis()) && (cal.getTimeInMillis()< curr.getTimeInMillis()))
{ System.out.println ("EVENT WILL TAKE PLACE FOR SURE WITHIN THE NEXT 10 DAYS!!");}
else
{ System.out.println ("EVENT WILL *NOT* TAKE PLACE WITHIN THE NEXT 10 DAYS");}
ALRIGHT GUYS AND GIRLS I HOPE THAT HELPS. A BIG HUG FOR YOU ALL AND GOOD LUCK WITH YOUR PROJECTS!
PEACE.
YOAV.
If the comparison should involve only the year, month and day then you can use this method for check if c1 is before c2. Ugly, but works.
public static boolean before(Calendar c1, Calendar c2){
int c1Year = c1.get(Calendar.YEAR);
int c1Month = c1.get(Calendar.MONTH);
int c1Day = c1.get(Calendar.DAY_OF_MONTH);
int c2Year = c2.get(Calendar.YEAR);
int c2Month = c2.get(Calendar.MONTH);
int c2Day = c2.get(Calendar.DAY_OF_MONTH);
if(c1Year<c2Year){
return true;
}else if (c1Year>c2Year){
return false;
}else{
if(c1Month>c2Month){
return false;
}else if(c1Month<c2Month){
return true;
}else{
return c1Day<c2Day;
}
}
}
used compareTo method ..and this returns integer value .if returns -ve the days before in current date else return +ve the days after come current date

Categories