This question already has answers here:
Closed 12 years ago.
Possible Duplicate:
How can I increment a date by one day in Java?
I have an existing date object that I'd like to increment by one day while keeping every other field the same. Every example I've come across sheds hours/minutes/seconds or you have to create a new date object and transfers the fields over. Is there a way you can just advance the day field by 1?
Thanks
EDIT: Sorry i didn't mean increment the value of the day by one, i meant advance the day forward by 1
Calendar c = Calendar.getInstance();
c.setTime(yourdate);
c.add(Calendar.DATE, 1);
Date newDate = c.getTime();
The Date object itself (assuming you mean java.util.Date) has no Day field, only a "milliseconds since Unix Epoch" value. (The toString() method prints this depending on the current locale.)
Depending of what you want to do, there are in principle two ways:
If you want simply "precisely 24 hours after the given date", you could simply add 1000 * 60 * 60 * 24 milliseconds to the time value, and then set this. If there is a daylight saving time shift between, it could then be that your old date was on 11:07 and the new is on 10:07 or 12:07 (depending of the direction of shift), but it still is exactly 24 hours difference.
private final static long MILLISECONDS_PER_DAY = 1000L * 60 * 60 * 24;
/**
* shift the given Date by exactly 24 hours.
*/
public static void shiftDate(Date d) {
long time = d.getTime();
time += MILLISECONDS_PER_DAY;
d.setTime(time);
}
If you want to have "the same time on the next calendar day", you better use a Calendar, like MeBigFatGuy showed. (Maybe you want to give this getInstance() method the TimeZone, too, if you don't want your local time zone to be used.)
/**
* Shifts the given Date to the same time at the next day.
* This uses the current time zone.
*/
public static void shiftDate(Date d) {
Calendar c = Calendar.getInstance();
c.setTime(d);
c.add(Calendar.DATE, 1);
d.setTime(c.getTimeInMillis());
}
If you are doing multiple such date manipulations, better use directly a Calendar object instead of converting from and to Date again and again.
org.apache.commons.lang.time.DateUtils.addDays(date, 1);
Related
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.
I have faced the same problem many times.
The Same Problem was With This Question and Got Solution Like the Same,
How to compare known hours ad current hour in android?
Problem :
When I use Calendar calCurr = Calendar.getInstance(); to get the Calendar object of current date and time, It always return me wrong.
I have put logs and checked it and to make it correct I had to add in years and months and then I got the correct object for Current Date and Time.
See My Example :
Calendar calCurr = Calendar.getInstance();
Log.i("Time in mili of Current - Normal", ""+calCurr.getTimeInMillis());
// see what it gives? dont know why?
Date date = new Date();
calCurr.set(date.getYear()+1900, date.getMonth()+1, date.getDate(), date.getHours(), date.getMinutes(), date.getSeconds());
// so added one month to it
Log.i("Time in mili of Current - after update", ""+calCurr.getTimeInMillis());
// now get correct
Question :
Why it's giving the wrong output?
Is it a bug in there or My concept about the Calendar class is wrong?
tell me what should have been done
for that?
It works perfectly as expected if you change to getDate() it outputs :
Time in mili of Current - Normal Wed Apr 04 11:34:34 BST 2012
Time in mili of Current - after update Fri May 04 11:34:34 BST 2012
What do you expect ? And in milleseconds it also equals 30 days :
Time in mili of Current - Normal 1333535834557
Time in mili of Current - after update 1336127834557
and the calculation is (difference, divided by milliseconds in a day) :
1336127834557 - 1333535834557 = 2 592 000 000
2592000000 / 86400000 = 30
And todays date in milliseconds after 1970 is 1333536754 ... which fits, I don't see a problem.
EDIT
Your Problem is you are setting Month like 3 for march...there you need to set 2..cause months are indexed from 0 to 11.
Do not use date.getXXX(). Do not use any setter or getter except Date.getTime(). They are all deprecated. Using them would cause unexpected results.
If you call Calendar.getInstance(), it is already set to the current date. If you want to set or add days, months, whatever, set them on the calendar.
E.g. calCurr.set(Calendar.MONTH,2) or calCurr.add(Calendar.DAY,1).
It is NOT a bug, the Calendar is returning what it should (at least here it is).
Calendar calCurr = Calendar.getInstance();
Log.i("Time in mili of Current - Normal", ""+calCurr.getTimeInMillis());
// see what it gives? dont know why?
I got 1333546375707 milliseconds, which is the correct value (also calculated by hand).
Which value are you expecting here? How you know it is wrong?
Date date = new Date();
calCurr.set(date.getYear()+1900, date.getMonth()+1, date.getDate(), date.getHours(), date.getMinutes(), date.getSeconds());
// so added one month to it
Why adding ONE to the month? Month of both Date and Calendar are zero-based - no need to add 1.
EDIT
Calculating by hand (approximated):
2012 - 42 years * 365.24 days/year * 86400 seconds/day
April - (31 + 29 + 31) days * 86400
4th - 3 days * 86400
13:30 - 13.5 hours * 3600 seconds/hour
====================
1333553112 seconds
Calendar months are zero-indexed. So when want to set for March its 2 not 3
Also, Don't set year, month and date from the Date object. If you must initialise a Calendar to a date, do it like this:
Calendar cal = Calendar.getInstance();
cal.setTime(date);
be aware that your Date object might be a different locale to what you think it is.
When Calendar object is created by using Calendar.getInstance() the instance variable "time" in the Calendar object is set and this value will get changed only if you use
Calendar.setTimeInMillis() function.
Code snippet from Calendar object:
public long getTimeInMillis() {
if (!isTimeSet) {
updateTime();
}
return time;
}
Here "isTimeSet" will become "true" when Calendar.getInstance() is called and it returns "time" every time without updating the time.
This is the reason you get the same value of time every time you call
calCurr.getTimeInMillis();
Hope this helps.
It's the weird implementation of Calendar.
For some reasons January is month 0, and years are not very logical as well.
I recommend Joda time library.
We are using below lines of code for finding current date and time It's working fine our side.
java.util.Calendar calc = java.util.Calendar.getInstance();
int day = calc.get(java.util.Calendar.DATE);
int month = calc.get(java.util.Calendar.MONTH)+1;
int year = calc.get(java.util.Calendar.YEAR);
String dayStr,monthStr;
if(day<10){
dayStr = "0"+day;
}else{
dayStr = ""+day;
}
if(month<10){
monthStr = "0"+month;
}else{
monthStr = ""+month;
}
/*String currentdate = monthStr+"/"+dayStr+"/"+year+" ";*/
String currentdate = dayStr+"/"+monthStr+"/"+year+" ";
/*String currenttime = currentdate + String.valueOf(calc.get(java.util.Calendar.HOUR_OF_DAY))+ ":"+
String.valueOf(calc.get(java.util.Calendar.MINUTE))+":"+String.valueOf(calc.get(java.util.Calendar.SECOND));*/
return currentdate;
Java Date Based API is not properly designed.
in future versions I think some problems of The API are planned to address.
I would recommend to use JodaTime.
How can I learn how many days passed from a spesific date? Which package i need to use and how?
Just for the protocol - i love java.util.concurrent.TimeUnit for that things.
Date d1 = ...
Date d2 = ...
long dif = d1.getTime() - d2.getTime();
long days = TimeUnit.MILLISECONDS.toDays(dif);
So basically exactly what the answer from morja is, but using TimeUnit for calculating time things around. Having values like 24, 60 etc. directly in your code violates Java Code Conventions (which only allow -1, 0 and 1 directly in code) and is harder to read.
EDIT My previous answer was only valid within a year.
You can use the milliseconds difference like this:
Date date1 = // some date
Date date2 = // some other date
long difference = date2.getTime() - date1.getTime();
long differenceDays = difference / (1000 * 60 * 60 * 24);
Basically the same as timbooo answered, just a shorter way.
Check out this example by kodejava.org
Jodatime makes such calculations a lot simpler:
Date now = // some Date
Date then = // some Date
int days = Days.daysBetween(new DateTime(now), new DateTime(then)).getDays();
In fact, you should create instances of Calendar from both of the dates, getTimeInMillis() from both of them (that is, time in milliseconds since 1970), substract one from the other, divide by 1000/seconds-a-minute/minute-an-hour/hour-a-day. There is your answer ;)
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
public class test {
/*
* Calculate the difference between two date/times *
*
*/
private static long dateDiff(Date toDate, Date fromDate) {
Calendar cal = Calendar.getInstance();
cal.setTime(toDate);
long ms = cal.getTimeInMillis();
cal.setTime(fromDate);
ms -= cal.getTimeInMillis();
return ms;
}
public static void main(String[] args) {
SimpleDateFormat sdf = new SimpleDateFormat("hh:mm:ss");
Date d1 = null;
Date d2 = null;
try {
d1 = sdf.parse("11:00:00");
d2 = sdf.parse("10:00:00");
} catch (Exception e) {
e.printStackTrace();
}
long result = dateDiff(d1, d2);
Date time = new Date(result);
System.out.println(time);
}
}
When I run it I get this result :
Thu Jan 01 02:00:00 CET 1970
I would expect 1 hour difference ?! again a problem with Timezone??
Any idea how I can fix it.
thx all
I don't know what you expect this to do, but what you are actually doing is outputting the date corresponding to one hour after midnight on Jan 1 1970, using the default timezone.
You seem to want to Date to represent a duration (i.e. a number of seconds). It doesn't do that, and neither will the Date formatters render a Date as a duration.
I need the time difference between two Date fields and then put it in MySql (time format)
For what you are trying to do, you need calculate the duration value as a long, then use the java.sql.Time(long) constructor to create a Time object. You can either serialize this object using its toString() method or use it as a parameter in a JDBC prepared statement.
It turns out that my advice above is incorrect too.
Your real problem is that the SQL Time type is for representing times ... not durations. In fact, SQL does not have a dedicated duration type, so the best you can do is represent the duration as an integer number of seconds or milliseconds or whatever.
(For the more general case, the Joda Time libraries are generally thought to provide the best APIs for manipulating dates, times and related temporal values. But for this simple case, the standard J2SE libraries should suffice ... provided that you use them correctly.)
The problem is that a difference of two Date types can not be represented by another Date type.
Why don't you just take the milliseconds of both dates and substract them from each other?
Calendar cal = Calendar.getInstance();
cal.setTime(d1);
long d1ms = cal.getTimeInMillis();
cal.setTime(d2);
long d2ms = cal.getTimeInMillis();
long diffMs = d1ms - d2ms;
long diffHour = diffMs * 1000 * 60 * 60;
Hi try this setting timezone to GMT. Remove day, month in words in the resultant time difference. This method does nothing but assumes these many milliseconds since starting of time counter in java, which is 1st Jan 1970. So if your result says 3rd Jan 1970 means 3 days have passed since time counter started, which is perfect. You just need to interpret it properly, but formatting your answer
...
long result = dateDiff(d1, d2); //This is your code in main([])
SimpleDateFormat dateFormat = new SimpleDateFormat("HH:mm:ss SSS");
dateFormat.setTimeZone(TimeZone.getTimeZone("GMT"));
System.out.println(dateFormat.format(new Date(result )));
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!