This question already has answers here:
Get the number of weeks between two Dates.
(19 answers)
Closed 8 years ago.
Let's see if you can help me. I want to get the number of weeks (starting on monday and finishing on sunday) between two dates, d1 and d2. Let's suppose that d2 is earlier of d1. That part of the code is already programmed and working. My problem now is that I'm not being able to code correctly the week program. This is what I made for now:
public static void getFullWeeks(Calendar d1, Calendar d2){
int Weeks = 0;
Calendar date2 = d2;
Calendar addWeek = GregorianCalendar.getInstance();
addWeek.setTime(date2.getTime());
addWeek.add(Calendar.DATE, 6);
while(addWeek.before(d1) || addWeek.equals(d1)){
if(date2.get(Calendar.DAY_OF_WEEK) == Calendar.MONDAY){
Weeks++;
}
date2.add(Calendar.DATE,1);
}
System.out.println(
"The number of weeks (from monday to sunday) between both dates are: "
+ Weeks);
}
But the output is "0 weeks", so the program is not working. What's wrong? I'm not encountering the error and I'm not being capable to find a working solution for this problem.
Thank you!!
In Java 8 without external libraries you can do something like the following:
*Edited to account for week starting on Monday
// TechTrip - ASSUMPTION d1 is earlier than d2
// leave that for exercise
public static long getFullWeeks(Calendar d1, Calendar d2){
// In Java the week starts on Sunday from an integral perspective
// public final static int SUNDAY = 1;
// SEQUENTIAL UP TO
// public final static int SATURDAY = 7;
// make the starting date relative to the Monday we need to calculate from
int dayOfStartWeek = d1.get(Calendar.DAY_OF_WEEK);
// IF we have a partial week we should add an offset that moves the start
// date UP TO the next Monday to simulate a week starting on Monday
// eliminating partial weeks from the calculation
// NOTE THIS METHOD WILL RETURN NEGATIVES IF D1 < D2 after adjusting for
// offset
if (dayOfStartWeek == Calendar.SUNDAY) {
// add an offset of 1 day because this is a partial week
d1.add(Calendar.DAY_OF_WEEK, 1);
} else if (dayOfStartWeek != Calendar.MONDAY){
// add an offset for the partial week
// Hence subtract from 9 accounting for shift by 1
// and start at 1
// ex if WEDNESDAY we need to add 9-4 (WED Int Val) = 5 days
d1.add(Calendar.DAY_OF_WEEK, 9 - dayOfStartWeek);
}
Instant d1i = Instant.ofEpochMilli(d1.getTimeInMillis());
Instant d2i = Instant.ofEpochMilli(d2.getTimeInMillis());
LocalDateTime startDate = LocalDateTime.ofInstant(d1i, ZoneId.systemDefault());
LocalDateTime endDate = LocalDateTime.ofInstant(d2i, ZoneId.systemDefault());
return ChronoUnit.WEEKS.between(startDate, endDate);
}
Here's the main:
public static void main(String[] args) {
Calendar d1 = Calendar.getInstance();
Calendar d2 = Calendar.getInstance();
d2.add(Calendar.WEEK_OF_YEAR, 6);
System.out.println(
"The number of weeks (from monday to sunday) between both dates are: "
+ getFullWeeks(d1, d2));
}
The output is as follows if the start date is a MONDAY:
The number of weeks (from monday to sunday) between both dates are: 6
Note, I did not assign date d2 to d1, making it the same reference. In that case you would get 0.
*The ChronoUnit takes a Temporal which is simply a date, time or offset. They must be of the same type. Temporals can be manipulated with plus and minus.
It seems to me there are couple of little mistakes you made:
1.) Your output is 0 weeks because elsewhere in your code you must have called this method with your first argument, d1, earlier than the second, while in the method body, you assume that d2 is earlier than d1. Such mistakes are easily avoided by using meaningful argument names. Appropriate argument names in this case are for example start and end.
2) If you execute this method using arguments in which d2 is earlier than d1, your method would fall into an infinite loop. It looks to me that adding to date2 does not change the date in addWeek.
3) Your method counts the number of weeks from Tuesday to Monday instead of Monday to Sunday. To fix this, add seven days to addWeek instead of six, or change the while loop to check only if addWeek is before d1 and increment weeks on sunday.
Putting all this together, I believe this will give you what you're looking for:
public static void getFullWeeks(Calendar start, Calendar end)
{
System.out.println("The number of weeks (from monday to sunday) between both dates are: " + getNrWeeksBetween(start, end));
}
private static int getNrWeeksBetween(Calendar start, Calendar end)
{
int weeks = 0;
Calendar counter = new GregorianCalendar();
counter.setTime( start.getTime() );
counter.add(Calendar.DATE, 6);
while( counter.before(end) )
{
if(counter.get(Calendar.DAY_OF_WEEK) == Calendar.SUNDAY) weeks++;
counter.add(Calendar.DATE, 1);
}
return weeks;
}
Your algorithm's wrong; your while loop needs to compare the same Calendar object you're modifying, but you don't do that, so you either have an infinite loop or you exit immediately with a return value of 0, depending on whether addDate is before or after d1 (since neither one changes). Your code should be:
public static void getFullWeeks(Calendar d1, Calendar d2){
int Weeks = 0;
Calendar addWeek = GregorianCalendar.getInstance();
addWeek.setTime(d2.getTime());
addWeek.add(Calendar.DATE, 6);
while(addWeek.before(d1) || addWeek.equals(d1)){
if(addWeek.get(Calendar.DAY_OF_WEEK) == Calendar.MONDAY){
Weeks++;
}
addWeek.add(Calendar.DATE,1);
}
System.out.println(
"The number of weeks (from monday to sunday) between both dates are: "
+ Weeks);
}
Related
I'm trying to find how many months are between 2 dates. My code is something like this right now
ChronoUnit.MONTHS.between(d1, d2)
The problem is that the result is a long. For example if the dates differ only in a few days I should get a result something like 0.34 instead of 0.
Also I need my code to account for the calendar, I cant assume each month has 31 days.
Diff between 1999-05-12 and 1999-08-24
Assuming all months have 31 days for simplicity
result = (19/31 + 31/31 + 31/31 + 24/31) = 2.793
According to the calendar we replace the 31s with the correct number of days for that specific year and month
Here is my solution:
public static double monthsBetween(LocalDate start, LocalDate end) {
if (start.isAfter(end)) throw new IllegalArgumentException("Start must be before end!");
var lastDayOfStartMonth = start.with(TemporalAdjusters.lastDayOfMonth());
var firstDayOfEndMonth = end.with(TemporalAdjusters.firstDayOfMonth());
var startMonthLength = (double)start.lengthOfMonth();
var endMonthLength = (double)end.lengthOfMonth();
if (lastDayOfStartMonth.isAfter(firstDayOfEndMonth)) { // same month
return ChronoUnit.DAYS.between(start, end) / startMonthLength;
}
long months = ChronoUnit.MONTHS.between(lastDayOfStartMonth, firstDayOfEndMonth);
double startFraction = ChronoUnit.DAYS.between(start, lastDayOfStartMonth.plusDays(1)) / startMonthLength;
double endFraction = ChronoUnit.DAYS.between(firstDayOfEndMonth, end) / endMonthLength;
return months + startFraction + endFraction;
}
The idea is that you find the last day of start's month (lastDayOfStartMonth), and the first day of end's month (firstDayOfEndMonth) using temporal adjusters. These two dates are very important. The number you want is the sum of:
the fractional number of a month between start and lastDayOfStartMonth
the whole number of months between lastDayOfStartMonth and firstDayOfEndMonth.
the fractional number of a month between firstDayOfEndMonth and end.
Then there is the edge case of when both dates are within the same month, which is easy to handle.
By using this definition, the nice property that the number of months between the first day of any two months is always a whole number is maintained.
Note that in the first calculation, you have to add one day to lastDayOfStartMonth, because ChronoUnit.between treats the upper bound as exclusive, but we actually want to count it as one day here.
To approach this problem, you need to consider the following cases:
dates belong to the same year and month;
dates belong to different year and/or month;
dates are invalid.
When dates belong to the same year and month, then the result would be the difference in days between the two dates divided by the number of days in this month, which can be found using LocalDate.lengthOfMonth().
In the general case, the range of dates can be split into three parts:
two fractional parts at the beginning and at the end of the given range of dates (both could be evaluated using the approach for the simplest case when both data belong to the same year/month)
the whole part, we can use ChronoUnit.MONTHS.between() to calculate it.
Here's how implementation might look like (d1 - inclusive, d2 - exclusive):
public static double getFractionalMonthDiff(LocalDate d1, LocalDate d2) {
if (d1.isAfter(d2)) throw new IllegalArgumentException(); // or return a value like -1
if (d1.getYear() == d2.getYear() && d1.getMonth() == d2.getMonth()) { // dates belong to same month and year
return getFractionalPartOfMonth(d2.getDayOfMonth() - d1.getDayOfMonth(), d1.lengthOfMonth());
}
int monthLen1 = d1.lengthOfMonth();
return getFractionalPartOfMonth(monthLen1 - (d1.getDayOfMonth() - 1), monthLen1) // from the given day of month of the First Date d1 Inclusive to the Last day of month
+ getFractionalPartOfMonth(d2.getDayOfMonth() - 1, d2.lengthOfMonth()) // from the First day of month to given day of month of the Second Date d2 Exclusive (for that reason 1 day was subtracted, and similarly on the previous line 1 day was added)
+ ChronoUnit.MONTHS.between(d1.withDayOfMonth(monthLen1), d2.withDayOfMonth(1));
}
public static double getFractionalPartOfMonth(int daysInterval, int monthLength) {
return daysInterval / (double) monthLength;
}
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
This question already has answers here:
How can I pad an integer with zeros on the left?
(18 answers)
Adding zero to a single digit number, Is it possible?
(2 answers)
Generate random date of birth
(15 answers)
Closed 5 years ago.
I want to generate random DOB for the given range of year. So I tried the below code
private static String randomDataOfBirth(int yearStart, int yearEnd)
{
GregorianCalendar gc = new GregorianCalendar();
int year = randBetween(yearStart, yearEnd);
gc.set(Calendar.YEAR, year);
int dayOfYear = randBetween(1, gc.getActualMaximum(Calendar.DAY_OF_YEAR));
gc.set(Calendar.DAY_OF_YEAR, dayOfYear);
String date = null;
if(gc.get(Calendar.MONTH) == 0)
{
date = gc.get(Calendar.YEAR) + "-" + 1 + "-" + gc.get(Calendar.DAY_OF_MONTH);
}else
{
date = gc.get(Calendar.YEAR) + "-" + gc.get(Calendar.MONTH) + "-" + gc.get(Calendar.DAY_OF_MONTH);
}
return date;
}
private static int randBetween(int start, int end) {
// TODO Auto-generated method stub
return start + (int)Math.round(Math.random() * (end - start));
}
Main:-
public static void main(String[] args) {
String dob = randomDataOfBirth(1899, 1937);
System.out.println(dob);
}
I can be able to generate the random DOB. But only for the Month and Day, I want to add a prefix '0' for the range from 1 to 9
Month - 01, 02, 03 and ... up to 09
Day - 01, 02, 03 and ... up to 09
Apart from the desired formatting of you date I see some other problems with your code that I think you would want to address:
Assuming you want a usual month number, 01 for January through 12 for December, your handling of the month number is not correct. get(Calendar.MONTH) gives you a 0-based month: 0 for January through 11 for December. Therefore, your code not only will never give you 12 as month and 1 all too often. It will also give you non-existing dates. I have seen 1905-2-31 and 1929-4-31 (because you get 2 for March, which we interpret as February, etc.).
Possibly unimportant, your distribution gives each day in a leap year slightly smaller probablity than other days.
If you can, I suggest you use LocalDate. The class was introduced in Java 8:
private static String randomDataOfBirth(int yearStartInclusive, int yearEndExclusive) {
LocalDate start = LocalDate.ofYearDay(yearStartInclusive, 1);
LocalDate end = LocalDate.ofYearDay(yearEndExclusive, 1);
long longDays = ChronoUnit.DAYS.between(start, end);
int days = (int) longDays;
if (days != longDays) {
throw new IllegalStateException("int overflow; too many years");
}
int day = randBetween(0, days);
LocalDate dateOfBirth = start.plusDays(day);
return dateOfBirth.toString();
}
This gives you evenly distributed, correct dates formatted with 2 digits for month and day-of-month, e.g., 1926-07-05.
If you want to avoid the overflow check, you may of course rewrite your randBetween() to handle longs.
If you cannot use Java 8, you can do something similar with GregorianCalendar and SimpleDateFormat. Counting the exact number of days from lower to upper bound is complicated, though, so you will probably want to stick to your way of picking the date. SimpleDateFormat can still give you correct dates formatted with two digits for month and day. Edit: In your class, declare:
static DateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
Now just substitute your if-else statement with this:
String date = formatter.format(gc.getTime());
If your randomDataOfBirth() may be accessed from more than one thread, this won’t work since SimpleDateFormat is not thread-safe. If so, each thread should have its own SimpleDateFormat instance.
With Java7 you can try with something like this:
public class DobMaker
{
public String getDOB(int min, int max)
{
Calendar calendar = Calendar.getInstance(TimeZone.getTimeZone("UTC"));
int year = min + new Random().nextInt(max - min + 1);
calendar.set(Calendar.YEAR, year);
int day = 1+new Random().nextInt(calendar.getActualMaximum(Calendar.DAY_OF_YEAR));
calendar.set(Calendar.DAY_OF_YEAR, day);
return new SimpleDateFormat("yyyy-MM-dd").format(calendar.getTime());
}
public static void main(String[] args)
{
DobMaker d = new DobMaker();
System.out.println(d.getDOB(1970, 1980));
System.out.println(d.getDOB(1970, 1971));
System.out.println(d.getDOB(2007, 2016));
}
}
Is it possible to add weekdays to joda time?
For instance, if current date is Friday 01/03, date + 1 should return Monday 04/03, rather than 02/03.
As far as I know there is no built-in method to automatically do this for you in Joda Time. However, you could write your own method, that increments the date in a loop until you get to a weekday.
Note that, depending on what you need it for exactly, this could be (much) more complicated than you think. For example, should it skip holidays too? Which days are holidays depends on which country you're in. Also, in some countries (for example, Arabic countries) the weekend is on Thursday and Friday, not Saturday and Sunday.
LocalDate newDate = new LocalDate();
int i=0;
while(i<days)//days == as many days as u want too
{
newDate = newDate.plusDays(1);//here even sat and sun are added
//but at the end it goes to the correct week day.
//because i is only increased if it is week day
if(newDate.getDayOfWeek()<=5)
{
i++;
}
}
System.out.println("new date"+newDate);
Be aware that iterating through adding N days one at a time can be relatively expensive. For small values of N and/or non performance sensitive code, this is probably not an issue. Where it is, I'd recommend minimizing the add operations by working out how many weeks and days you need to adjust by:
/**
* Returns the date that is {#code n} weekdays after the specified date.
* <p>
* Weekdays are Monday through Friday.
* <p>
* If {#code date} is a weekend, 1 weekday after is Monday.
*/
public static LocalDate weekdaysAfter(int n, LocalDate date) {
if (n == 0)
return date;
if (n < 0)
return weekdaysBefore(-n, date);
LocalDate newDate = date;
int dow = date.getDayOfWeek();
if (dow >= DateTimeConstants.SATURDAY) {
newDate = date.plusDays(8 - dow);
n--;
}
int nWeeks = n / 5;
int nDays = n % 5;
newDate = newDate.plusWeeks(nWeeks);
return ( (newDate.getDayOfWeek() + nDays) > DateTimeConstants.FRIDAY)
? newDate.plusDays(nDays + 2)
: newDate.plusDays(nDays);
public LocalDate getBusinessDaysAddedDate(LocalDate localDate, int businessDays){
LocalDate result;
if(localDate.getDayOfWeek().getValue() + businessDays > 5) {
result = localDate.plusDays(2);
}
result = localDate.plusDays(businessDays);
return result;
}
In order to work with Date instead of LocalDate, refer https://stackoverflow.com/a/47719540/12794444 for the conversions.
Class YearMonthDay is deprecated and you shouldn't use it. If you change to simple DateTime you can obtain the week day by calling:
dateTime.getDayOfWeek();
For Friday it will be 5.
One of the approaches can be making a custom addDays method which should look something like that:
addDays(DateTime dateTime, int days) {
for(int i=0;i<days;i++){
dateTime.plusDays(1);
if(dateTime.getDayOfWeek()==6) dateTime.plusDays(2); // if Saturday add 2 more days }
}
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