setMaxDate value cannot be set to 18 year back - java

I am trying to set the maxdate value to 18year before, but I couldn't do it.
setMaxDate(new Date().getTime()-18*365*24*60*60*1000);
I am using the above method and I would like to use only this menthod. Kindly help

18*365*24*60*60*1000 is a number too large to fit in a 32-bit signed integer. Change it to a 64-bit signed long integer: 18*365*24*60*60*1000L (notice the L).
But there are better methods to go 18 years back, e.g.
Calendar c = Calendar.getInstance(); // current date
c.add(Calendar.YEAR, -18);
Date t = c.getTime(); // to convert to Date

If you are passing Date parameter to setMaxDate function then it should be
setMaxDate( new Date( new Date().getTime()- 1L * 18 * 365 * 24 * 60 * 60 * 1000 ) );

Related

Unable subtract days from date in java [duplicate]

This question already has answers here:
How to subtract X days from a date using Java calendar?
(11 answers)
Closed 6 years ago.
I want to subtract days from date in java. But I dont want to use external libraries. I have referred some of questions from stackoverflow but they are suggesting to use external libraries. So I have applied following logic
noOfDays = 24;
Date compareDate = new Date(currentDate - noOfDays * 24 * 60 * 60 * 1000);
System.out.println("compare date " + compareDate);
It is working fine till 24 days.But after 24 days it is giving unexpected result. Is there any solution to this ?
Use java.util.Calendar.
Something like that:
Calendar c = new Calendar()
c.setTime(currentDate);
c.add(Calendar.DAY_OF_MONTH, noOfDays)
compareDate = c.getTime()
You can use a LocalDate (which is part of the JDK since Java 8):
LocalDate today = LocalDate.now();
LocalDate compareDate = today.minusDays(24);
You computation is about integers, which won't fit higher values than the max integer value.
Declare your variable as a long :
long noOfDays = 24;
Date compareDate = new Date(currentDate - noOfDays * 24 * 60 * 60 * 1000);
System.out.println("compare date " + compareDate);
However, as the comments said, this is not the best approach for substracting days, so have a look at better solutions in other answers.

Getting a correct date by adding substracting a number of milliseconds

Today is 18/12/2013.
I was testing this program where I wanted get another date by adding/substracting a number of milliseconds from System.currentMillis(). It works well when I shift the date in decembre but it doesn't work correctly for some similar values. For example the following code gives me 2013 12 20 as the result! I wonder, no I still wonder how it could be possible! or I'm making a mistake?
public class CreateDirFiles {
public static final String PLOG_DIR = "ProductLog";
private SimpleDateFormat dateFormatter = new SimpleDateFormat();
public CreateDirFiles() {
}
public void createDayDir(Date date){
dateFormatter.applyPattern("YYYY");
String year = dateFormatter.format(date);
dateFormatter.applyPattern("MM");
String month = dateFormatter.format(date);
dateFormatter.applyPattern("dd");
String day = dateFormatter.format(date);
System.out.printf("%s %s %s\n", year, month, day);
}
public static void main(String... args){
CreateDirFiles dfc = new CreateDirFiles();
dfc.createDayDir(new Date(System.currentTimeMillis() -
((long)( 48 * 24 * 3600 * 1000)) ));
}
}
This is the problem:
((long)( 48 * 24 * 3600 * 1000))
That's doing all the arithmetic in 32 bits, and then converting the (now truncated, as the result is too large for an int) result to a long. You want:
48L * 24 * 3600 * 1000
where the L suffix means that it'll use a long for the value 48.
However, you really don't want to do this at all - you want to use Joda Time which is a much nicer API for date/time work. You really don't want to have to mess around with the low level stuff at all.
LocalDate date = ...;
LocalDate twoDaysLater = date.minusDays(48);
If you really want to stick with the built-in API, then use Calendar. At the very least use the TimeUnit enum, which will allow:
long millisFor48Days = TimeUnit.DAYS.toMillis(48);
You also need to consider the time zone - while "today" may be the 18th of December for you, it isn't elsewhere in the world.

Android Calendar is not giving expected results

I am passing values to calendar instance, but don't know why it is not performing as expected. I want to add one day to a specific date and then use that date.
Log.v("data going to calendar==",
"year="+Integer.parseInt(fy)+
"month="+Integer.parseInt(fm)-1)+
"day="+Integer.parseInt(fd)+
"hh="+Integer.parseInt(fh)+
"mm="+Integer.parseInt(fmn));
c.set(
Integer.parseInt(fd),
Integer.parseInt(fm)-1,
Integer.parseInt(fy),
Integer.parseInt(fh),
Integer.parseInt(fmn));
c.add(Calendar.DAY_OF_MONTH,1);
Log.v("data coming from calendar==",
"year = " + c.get(Calendar.YEAR)+
"month ="+ c.get(Calendar.MONTH)+
"day ="+c.get(Calendar.DATE)+
"hh="+c.get(Calendar.HOUR)+
"mm="+c.get(Calendar.MINUTE));
output is:
data gng to calendar==year = 2013month =7day =29hh=12mm=0
data cmng from calendar==year = 35month =1day =4hh=0mm=0
i run that code by putting comment on code to add one day, but the results are still same except for day, it means adding one day is working perfectly --->
year = 35month =1day =3hh=0mm=0
You call the set() method with the wrong parameters. According to the documentation the order must be year, month, date as first three parameters and you call it with date, month, year as the first parameters.
If you change your code to
c.set(Integer.parseInt(fy),
Integer.parseInt(fm)-1,
Integer.parseInt(fd),
Integer.parseInt(fh),
Integer.parseInt(fmn));
it should work as intended.
The strange values are because it treats 2013 as the day which is approx. 6 years that are added to the date.
If you want to add a day - 24 hours - to a date, add it as milliseconds: 1 day = 24 * 60 * 60 * 1000 milliseconds.
Calendar c = Calendar.getInstance();
//Set calendar's fields here
long time = c.getTimeInMilliseconds();
long nextDay = time + 24 * 60 * 60 * 1000;
c.setTimeInMillis(nextDay);

How do I increment a java.sql.Timestamp by 14 days?

I have an app that takes a Timestamp as a boundary for the start date and end date of a sql selection, I want to populate a hashmap with weeks this year since the first monday of the year as the values and the week number as the keys. I'm finding it really hard to work with timestamps and I don't feel very good about adding 86,400,000 seconds to it to increment the day, as this doesn't account for the leap days, hours, seconds.
I plan on adding 13 days 23 hours, 59 minutes and 59 seconds to it so that I can lookup the start date in the map by the week as the key, then use the start date to get the end date.
So I'm looking to try to get something like this:
Week startDate endDate
1 2011-01-03 00:00:00 2011-01-16 23:59:59
2 2011-01-17 00:00:00 2011-01-30 23:59:59
With the first two columns in the Map and the last one being calculated after looking it up. How do I safely increment a java.sql.Timestamp?
java.sql.Timestamp ts = ...
Calendar cal = Calendar.getInstance();
cal.setTime(ts);
cal.add(Calendar.DAY_OF_WEEK, 14);
ts.setTime(cal.getTime().getTime()); // or
ts = new Timestamp(cal.getTime().getTime());
This will correctly cater for daylight-time transitions in your default Timezone. You can tell the Calendar class to use a different Timezone if need be.
It worth noting that 14 days is not always 14 * 24 * 3600 seconds. When you have daylight savings, this can be an hour shorter or longer. Historically it can be much more complex than that.
Instead I would suggest using JodaTime or the Calendar to perform the time zone dependant calculation.
Java 8
Timestamp old;
ZonedDateTime zonedDateTime = old.toInstant().atZone(ZoneId.of("UTC"));
Timestamp new = Timestamp.from(zonedDateTime.plus(14, ChronoUnit.DAYS).toInstant());
private Long dayToMiliseconds(int days){
Long result = Long.valueOf(days * 24 * 60 * 60 * 1000);
return result;
}
public Timestamp addDays(int days, Timestamp t1) throws Exception{
if(days < 0){
throw new Exception("Day in wrong format.");
}
Long miliseconds = dayToMiliseconds(days);
return new Timestamp(t1.getTime() + miliseconds);
}
Timestamp my14DaysAfter = Timestamp.valueOf(myTimestamp.toLocalDateTime().plusDays(14));

Java Date problems, finding the date X days ago

Date nowdate = new Date();
long nowms = nowdate.getTime();
long differencems = numdaysback * 24 * 60 * 60 * 1000;
long thenms = nowms - differencems;
Date thendate = new Date(thenms);
If numdaysback is 365, then I would suppose that thendate would be one year ago. but it's not... it's about three weeks ago?!?
NUMDAYSBACK: 365
NOWDATE: Wed Jun 22 20:31:58 SGT 2011
NOWMS: 1308745918625
DIFFERENCEMS: 1471228928
THENMS: 1307274689697
THENDATE: Sun Jun 05 19:51:29 SGT 2011
How about:
Calendar cal = Calendar.getInstance();
cal.add(Calendar.YEAR, -1);
Date thendate = cal.getTime();
Returns the same time of day regardless of DST or leap years, is shorter and clearer...
Generally Calendar is the way to go in such cases (unless you use a 3rd party library like Joda Time). You can use it for all kinds of calculations: add N days/hours/months/seconds, truncate time to a whole hour etc. - stuff that would be too much pain with long only.
Regarding your original question, it seems to be a victim of integer overflow. It works if the multiplication explicitly uses long:
long differencems = 365 * 24 * 60 * 60 * 1000L;
If you are using Java 8 and up, you can use the newer java.time library to do this a bit more cleanly.
Date xDaysAgo = Date.from( Instant.now().minus( Duration.ofDays( x ) ) );
Just try this:
long differencems = numdaysback * 24L * 60 * 60 * 1000;
With the new code you will not loose the digits due to integer multiplication.
Since we have marked the literal 24 as long, the multiplication will be done by auto converting the first operand numdaysback into long. The rest of the multiplication will also be done on long operands.
This line:
long differencems = numdaysback * 24 * 60 * 60 * 1000;
the RHS should be: 31536000000. You have something much less, the reason being the RHS is being evaluated as an int (as all the quantities are ints), and you are exceeding MAX_INT. To correct to this:
long differencems = numdaysback * 24 * 60 * 60 * 1000l;
Note the "l" which makes 1000 be a long - now the RHS will be evaluated as a long.
The Date class is (informally) deprecated. The API has so many faults, that it is really difficult to get Dates/Times right with it. The easiest example is something like your code for differencems. It fails, if the time inbetween contains a daylight savings switch (if you don't use UT) and will always fail to take care of leap seconds.
If your application depends on correct dates, you might want to use Joda Time.

Categories