Subtract days from Current Date using Calendar Object - java

I am trying to subtract days from the current date using the java.util.Calendar object. My problem here is the days to subtract can be positive or negative. My code is as follows
public class Test {
public static void main(String[] args) {
int pastValidationDays=2;
Calendar calendar = Calendar.getInstance();
calendar.add(Calendar.DAY_OF_MONTH, - pastValidationDays);
}
}
As per the above code if the date is 20/1/2015 it will give me 18/1/2015
Now say if the pastValidationDays= -2(negative value) then also it should subtract from the current date. As per the above code if i say
Calendar calendar = Calendar.getInstance();
calendar.add(Calendar.DAY_OF_MONTH, - pastValidationDays);
then it is adding up the days instead of subtracting. Say if the current date 20/1/2015 it is giving me 22/1/2015. But in this case as well i need the date as 18/1/2015.
One of the way i am doing is as below
if (pastValidationDays < 0){
calendar.add(Calendar.DAY_OF_MONTH, pastValidationDays);
}else{
calendar.add(Calendar.DAY_OF_MONTH, -pastValidationDays);
}
Is this a good approach or can it be done this way
calendar.add(Calendar.DAY_OF_MONTH, - Math.abs(pastValidationDays));
I want to subtract the days using calendar object only. I do not want to use JODA time and other objects. Please suggest other approaches if any. Thanks in advance

Related

Android : Compare two dates with different time zones [duplicate]

I have 2 date object in the database that represent the company's working hours.
I only need the hours but since I have to save date. it appears like this:
Date companyWorkStartHour;
Date companyWorkEndHour;
start hours: 12-12-2001-13:00:00
finish hours: 12-12-2001-18:00:00
I have the timezone of the company and of the user. (my server may be in another timezone).
TimeZone userTimeZone;
TimeZone companyTimeZone;
I need to check if the user's current time (considering his timezone) is within the company working hours (considering the company's time zone).
How can I do it? I am struggling for over a week with Java calendar and with no success!
The java.util.Date class is a container that holds a number of milliseconds since 1 January 1970, 00:00:00 UTC. Note that class Date doesn't know anyting about timezones. Use class Calendar if you need to work with timezones. (edit 19-Jan-2017: if you are using Java 8, use the new date and time API in package java.time).
Class Date is not really suited for holding an hour number (for example 13:00 or 18:00) without a date. It's simply not made for that purpose, so if you try to use it like that, as you seem to be doing, you'll run into a number of problems and your solution won't be elegant.
If you forget about using class Date to store the working hours and just use integers, this will be much simpler:
Date userDate = ...;
TimeZone userTimeZone = ...;
int companyWorkStartHour = 13;
int companyWorkEndHour = 18;
Calendar cal = Calendar.getInstance();
cal.setTime(userDate);
cal.setTimeZone(userTimeZone);
int hour = cal.get(Calendar.HOUR_OF_DAY);
boolean withinCompanyHours = (hour >= companyWorkStartHour && hour < companyWorkEndHour);
If you also want to take minutes (not just hours) into account, you could do something like this:
int companyWorkStart = 1300;
int companyWorkEnd = 1830;
int time = cal.get(Calendar.HOUR_OF_DAY) * 100 + cal.get(Calendar.MINUTE);
boolean withinCompanyHours = (time >= companyWorkStart && time < companyWorkEnd);
Try something like this:
Calendar companyWorkStart = new GregorianCalendar(companyTimeZone);
companyWorkStart.setTime(companyWorkStartHour);
Calendar companyWorkEnd = new GregorianCalendar(companyTimeZone);
companyWorkEnd.setTime(companyWorkEndHour);
Calendar user = new GregorianCalendar(userTimeZone);
user.setTime(userTime);
if(user.compareTo(companyWorkStart)>=0 && user.compareTo(companyWorkEnd)<=0) {
...
}
I haven't tried the Joda library. This code should work.
public boolean checkUserTimeZoneOverLaps(TimeZone companyTimeZone,
TimeZone userTimeZone, Date companyWorkStartHour,
Date companyWorkEndHour, Date userCurrentDate) {
Calendar userCurrentTime = Calendar.getInstance(userTimeZone);
userCurrentTime.setTime(userCurrentDate);
int year = userCurrentTime.get(Calendar.YEAR);
int month = userCurrentTime.get(Calendar.MONTH);
int day = userCurrentTime.get(Calendar.DAY_OF_MONTH);
Calendar startTime = Calendar.getInstance(companyTimeZone);
startTime.setTime(companyWorkStartHour);
startTime.set(Calendar.YEAR, year);
startTime.set(Calendar.MONTH, month);
startTime.set(Calendar.DAY_OF_MONTH, day);
Calendar endTime = Calendar.getInstance(companyTimeZone);
endTime.setTime(companyWorkEndHour);
endTime.set(Calendar.YEAR, year);
endTime.set(Calendar.MONTH, month);
endTime.set(Calendar.DAY_OF_MONTH, day);
if (userCurrentTime.after(startTime) && userCurrentTime.before(endTime)) {
return true;
}
return false;
}
EDIT
Updated the code to reflect Bruno's comments. Shouldn't be taking the dates of the company work timings.
Hey I am not sure how you would do this using the Java calendar but I would highly recommend using the Joda Time package. It's a much simpler system to use and it gives you direct methods to extracts all subcomponents of data and time and even just to create simple time objects without the date involved. Then I imagine it would be a matter of comparing the 2 timezone differences and subtracting the difference from the JodaTime object.

Java date and age

I am using a JXDatepicker to get the birth date of a person, and what i have to do is set another JXDatepicker with the retirement date. So the idea here is to get the year of the birth date and to increment it with one year in a loop until the "person" reaches 60 years old and keep the same day and month of birth.. Or i think that's what i have to do. but i can't seem to find how to use the Calendar classes nor the DateFormat classes to do this calculation, i tried different things but nothing works, the closest i got is the date 01/01/1970, which can't be the person's retirement date since the birth date i'm testing is always in 2014 so it should be 2074.
So how can i do the calculation? I'd be grateful if someone could give me an example on how to do it.
(It might seem that i didn't do enough researches, but i did, and i don't find why i would mention what i found since it didn't help me)
You shouldn't write any loop to add 60 years to your date.
You can get a selected date from your JXDatePicker and do it like that:
final Calendar cal = Calendar.getInstance();
cal.setTime(date);
cal.add(Calendar.YEAR, 60);
final Date retirementDate = cal.getTime();
Why on earth would you have to add 1 in a loop 60 times? Why don't you just add 60?
import java.text.SimpleDateFormat;
import java.util.Calendar;
public class Main {
public static void main(String... args){
SimpleDateFormat df = new SimpleDateFormat("MM/dd/YYYY");
Calendar c = Calendar.getInstance();
System.out.println(df.format(c.getTime())); //prints 05/14/2014
c.add(Calendar.YEAR, 60);
System.out.println(df.format(c.getTime())); //prints 05/14/2074
}
}

Java: Customize adding 1 month to the current date

I've read around and basically I've figured out that the Calendar object is capable of adding 1 month to a date specified by using something like:
Calendar cal = Calendar.getInstance();
cal.add(Calendar.MONTH, 1);
Although I don't like its behavior whenever the date is on either the 30 or 31. If ever I add 1 month to 01/31/2012, the output becomes 02/29/2012. When I add 1 more month, it becomes 03/29/2012.
Is there anyway I can force 02/29/2012 to become 03/01/2012 automatically?
Basically this is what I want to happen:
Default date: 01/31/2012
Add 1 month: 03/01/2012
Add 1 more month: 03/31/2012
What you are asking for is some implicit knowledge that if the starting date is the last day of the month, and you add 1 month, the result should be the last day of the following month. I.e. the property "last-day-of-month" should be sticky.
This is not directly available in Java's Calendar, but one possible solution is to use Calendar.getActualMaximum(Calendar.DAY_OF_MONTH) to reset the day after incrementing the month.
Calendar cal = ...;
cal.add(Calendar.MONTH,1);
cal.set(Calendar.DAY_OF_MONTH,cal.getActualMaximum(Calendar.DAY_OF_MONTH));
You could even subclass GregorianCalendar and add a method
public Calendar endOfNextMonth() { ... }
to encapsulate the operation.
Well for add 30 days you can do something like this:
public static java.sql.Date sumarFechasDias(java.sql.Date fch, int days) {
Calendar cal = new GregorianCalendar();
cal.setTimeInMillis(fch.getTime());
cal.add(Calendar.DATE, days);
return new java.sql.Date(cal.getTimeInMillis());
}
if days=30, it will return your date with 30 days added.
It looks like you want the calendar to roll up to the beginning of the next month if the date of the next month is smaller than the date of the month before it. Here's how we'd do that:
Calendar cal = Calendar.getInstance();
int oldDay = cal.get(DAY_OF_MONTH);
cal.add(Calendar.MONTH, 1);
// If the old DAY_OF_MONTH was larger than our new one, then
// roll over to the beginning of the next month.
if(oldDay > cal.get(DAY_OF_MONTH){
cal.add(Calendar.MONTH, 1);
cal.set(Calendar.DAY, 1);
}

Help with java calendar logic

I am working with the Java Calendar class to do the following:
Set a start date
Set an end date
Any date within that range is a "valid" date
I have this somewhat working, and somewhat not. Please see the code below:
nowCalendar.set(Calendar.DATE, nowCalendar.get(Calendar.DATE) + offset);
int nowDay = nowCalendar.get(Calendar.DATE);
Calendar futureCalendar = Calendar.getInstance();
futureCalendar.set(Calendar.DATE, nowDay + days);
Date now = nowCalendar.getTime();
Date endTime = futureCalendar.getTime();
long now_ms = now.getTime();
long endTime_ms = endTime.getTime();
for (; now_ms < endTime_ms; now_ms += MILLIS_IN_DAY) {
valid_days.addElement(new Date(now_ms));
System.out.println("VALID DAY: " + new Date(now_ms));
}
Basically, I set a "NOW" calendar and a "FUTURE" calendar, and then I compare the two calendars to find the valid days. On my calendar, valid days will be shaded white and invalid days will be shaded gray. You will notice two variables:
offset = three days after the current selected date
days = the number of valid days from the current selected date
This works...EXCEPT when the current selected date is the last day of the month, or two days prior (three all together). I think that its the offset that is definitely screwing it up, but the logic works everywhere else. Any ideas?
Don't fiddle with milliseconds. Clone the nowCalendar, add 1 day to it using Calendar#add() in a loop as long as it does not exceed futureCalendar and get the Date out of it using Calendar#getTime().
Calendar clone = nowCalendar.clone();
while (!clone.after(futureCalendar)) {
validDays.add(clone.getTime());
clone.add(Calendar.DATE, 1);
}
(note that I improved validDays to be a List instead of the legacy Vector)
Use add instead of set in the first line, otherwise the month is not adjusted if you are at the month boundary:
nowCalendar.add(Calendar.DATE, offset);
public boolean isInRange(Date d)
{
Calendar cal = Calendar.getInstance();
cal.setTime(d);
return cal.after(startCal) && cal.before(endCal);
}
Here the startCal is the calendar instance of start time and endCal is end time.
I found the problem:
As soon as I set futureCalendar to be a clone of nowCalendar (plus the additional days), then it started working. Thanks for everyone's suggestions!

Java Calendar problem: why are these two Dates not equal?

import java.io.*;
public class testing {
public static void main(String a[]) throws Exception{
Date d1=new Date();
Thread.sleep(2000);
Date d2=new Date();
if(d1.equals(d2)){
System.out.println("Both equal");
}else{
System.out.println("Both not equal");
}
Calendar c1=Calendar.getInstance();
Calendar c2=Calendar.getInstance();
c1.setTime(d1);
c2.setTime(d2);
c1.clear(Calendar.HOUR);
c1.clear(Calendar.MINUTE);
c1.clear(Calendar.SECOND);
c2.clear(Calendar.HOUR);
c2.clear(Calendar.MINUTE);
c2.clear(Calendar.SECOND);
if(c2.compareTo(c1) == 0){
System.out.println("Cal Equal");
}else {
System.out.println("Cal Not Equal");
}
}
}
When I run the above code multiple times of which each time (for printing if conditions of date) 'Both not equal' is printed but (for if condition of Calendar) sometimes it prints 'Cal Equal' and sometimes 'Cal Not Equal'. Can anyone please explain me why this is so?
The main reason I was trying this because I want to compare two dates. Both have same day, month and Year but different time of the day when the objects were created. I want them to be compared equal(same). How should I do this?
Truncate the Milliseconds field
Calendars have milliseconds, too. Add this:
c1.clear(Calendar.MILLISECOND);
c2.clear(Calendar.MILLISECOND);
But it's easier to achieve that functionality using DateUtils.truncate() from Apache Commons / Lang
c1 = DateUtils.truncate(c1, Calendar.DATE);
c2 = DateUtils.truncate(c2, Calendar.DATE);
This removes all hours, minutes, seconds and milliseconds.
I believe Calendar also has Millisecond precision. If you want to continue your code, add
c1.clear(Calendar.MILLISECOND);
c2.clear(Calendar.MILLISECOND);
then try your comparison.
use JodaTime instead, its so much better (than the standard Date and Calendar) for manipulating dates and time.
You need to clear milleseconds
After
Calendar c1=Calendar.getInstance();
add
c1.clear();
That's a bit easier to type than c1.clear(Calendar.MILLISECOND);
Works a treat.
Reset time using the below method before compare dates
private Calendar resetHours(Calendar cal) {
cal.set(Calendar.HOUR, 0);
cal.set(Calendar.MINUTE, 0);
cal.set(Calendar.SECOND,0);
cal.set(Calendar.HOUR_OF_DAY,0);
cal.set(Calendar.MILLISECOND,0);
return cal;
}

Categories

Resources