I mentioned that one of the method in the production project work wrong with dates, but i can't just replace it, because it is in production for a long time. I've created a new method, that works correct, but i can't figure out why the first method work wrong.
Old method (that works wrong):
public static Integer getNumberOfDays(Date startDate, Date endDate) {
TimeZone.setDefault((TimeZone.getTimeZone("Europe/Moscow")));
startDate.setHours(00);
startDate.setMinutes(00);
startDate.setSeconds(00);
endDate.setHours(23);
endDate.setMinutes(59);
endDate.setSeconds(59);
Calendar cal1 = Calendar.getInstance();
cal1.setTime(startDate);
Calendar cal2 = Calendar.getInstance();
cal2.setTime(endDate);
Calendar date = (Calendar) cal1.clone();
int daysBetween = 0;
while (date.before(cal2)){
date.add(Calendar.DAY_OF_MONTH, 1);
daysBetween++;
}
return daysBetween;
}
New method:
public static Integer getNumberOfDaysSecondVersion(Date startDate, Date endDate) {
long difference = startDate.getTime() - endDate.getTime();
float daysBetween = (difference / (1000*60*60*24));
return (int) daysBetween > 0 ? (int) daysBetween : 0;
}
Here is how i call both:
DateFormat formated = new SimpleDateFormat("yyyy-MM-dd");
System.out.println(Calculation.getNumberOfDays(
formated.parse("2018-06-14"),
formated.parse("2018-06-06")
));
System.out.println(Calculation.getNumberOfDaysSecondVersion(
format.parse("2018-06-14"),
format.parse("2018-06-06"))
);
Output:
0
8
Please help.
Your old method is the correct one. When start date is after end date, it returns 0. This is the case in your call.
Your new method subtracts end date from start date, which is wrong, is should be the other way around. I also suspect that it will give surprises across transitions from and to summer time (DST). While Moscow currently doesn’t use summer time, it has done historically, at least until 2010, and may do again if politicians decide so.
That said, you should try if you can avoid the old and long outdated date and time classes DateFormat, SimpleDateFormat, Calendar, Date and TimeZone. Today we have so much better in java.time, the modern Java date and time API. Of course, in legacy code you have old-fashioned Date objects. When writing a new method, I recommend you convert those to the modern LocalDate and use ChronoUnit.DAYS.between().
ChronoUnit.DAYS.between(
LocalDate.parse( "2018-06-14" ) ,
LocalDate.parse( "2018-06-06" )
)
-8
Be aware that when the old method sets the default time zone, it affects all programs running in your JVM and may come as a nasty surprise to other parts of your program and to other programs.
You used a very different algorithm for the two versions.
The old version keeps adding days to the start date until it is after the end date.
The new version subtracts the end date from the start date and divides it by the number of milliseconds there are in a day.
This means that for the first version to work, the start date must be before the end date, and for the second version to work, the start date must be after the end date. The parameters you gave the the first version has the start date after the end date, making it return 0.
To fix this, you can just reverse the two arguments:
System.out.println(getNumberOfDays(
formated.parse("2018-06-06"),
formated.parse("2018-06-14")
));
Or, check which date comes first before calculating the difference between them.
By the way, your first version seems to output one more than your second version. You seem to want a result of 8 days. This means that your first version has an off-by-1 error. You can fix this by subtracting 1 from the counted result.
Remember to always work with java.time whenever you can!
Probably because startDate and endDate's timezones aren't affected by setting the default timezone, so that when you set Calendar times (in Moscow time) based on them, you're converting timezones, possibly turning 00:00:00 into the previous day 21:00:00 or something.
EDIT
Seeing your outputs, it became obvious... you're passing in a start date that is in the future compared to end date. The original method uses a loop that can only count up, while your new method takes the absolute value of the difference.
Related
I am working on a project in my CIS 163 class that is effectively a campsite reservation system. The bulk of the code was provided and I just have to add certain functionalities to it. Currently I need to be able to determine how much time has passed between 2 different GregorianCalendar instances (one being the current date, the other being a predetermined "check out") represented by days. I haven't been able to figure out quite how to do this, and was hoping someone here might be able to help me out.
The GregorianCalendar is old and you shouldn't really use it anymore. It was cumbersome and was replaced by the "new" java.time module since Java 8.
Still, if you need to compare using GC instances, you could easily calculate time using milliseconds between dates, like this:
GregorianCalendar date1 = new GregorianCalendar();
GregorianCalendar date2 = new GregorianCalendar();
// Adding 15 days after the first date
date2.add(GregorianCalendar.DAY_OF_MONTH, 15);
long duration = (date2.getTimeInMillis() - date1.getTimeInMillis() )
/ ( 1000 * 60 * 60 * 24) ;
System.out.println(duration);
If you want to use the new Time API, the following code would work.
LocalDate date1 = LocalDate.now();
LocalDate date2 = date1.plusDays(15);
Period period = Period.between(date1, date2);
int diff = period.getDays();
System.out.println(diff);
If you need to convert between the types (e.g. you're working with legacy code), you can do it like this:
LocalDate date3 = gcDate1.toInstant().atZone(ZoneId.systemDefault()).toLocalDate();
LocalDate date4 = gcDate2.toInstant().atZone(ZoneId.systemDefault()).toLocalDate();
Also I'm pretty sure this question must've been asked over and over again, so make sure you search properly before asking.
Since you have been forced to use the old and poorly designed GregorianCalendar class, the first thing you should do is convert each of the two GregorianCalendar objects to a modern type. Since Java 8 GregorianCalendar has a method that converts it to ZonedDateTime. Check the documentation, I include a link below.
Now that you’ve got two ZonedDateTime objects, there are different paths depending on your exact requirements. Often one will use Duration.between() for finding the duration, the amount of time between them in hours, minutes, seconds and fraction of second. If you know that you will always need just one of those time units, you may instead use for example ChronoUnit.HOURS.between() or ChronoUnit.MILLISECONDS.between(). If you need to count days, use ChronoUnit.DAYS.between().
If instead you need the time in months and days, you should instead use Period.between().
Links
Documentation:
GregorianCalendar (long outdated, don’t use unless forced to)
Duration
ChronoUnit
Period
Oracle tutorial: Date Time explaining how to use java.time, the modern Java date and time API to which ZonedDateTIme, Duration, ChronoUnit and Period belong.
I have written below code which is running, and giving output. But I'm not sure It's a right one.
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
Date date = new Date();
sdf.setTimeZone(TimeZone.getTimeZone("GMT-7"));
String value = sdf.format(date);
System.out.println(value);
Date date2 = sdf.parse(value);
long result = date2.getTime();
System.out.println(result);
return result;
The above code what I'm trying is, I just need to get the current time of GMT time zone and convert it as epoch format which is gonna used in Oracle db.
Can someone tell me that format, and the above code is right?
First, you should not store time since the epoch as a timestamp in your database. Look into the date-time datatypes that your DMBS offers. In Oracle I think that a date column will be OK. For most other DBMS you would need a datetime column. timestamp and timestamp with timezone may be other and possibly even sounder options depending on your exact requirements.
However, taking your word for it: Getting the number of milliseconds since the epoch is simple when you know how:
long millisecondsSinceEpoch = System.currentTimeMillis();
System.out.println(millisecondsSinceEpoch);
This just printed:
1533458641714
The epoch is defined in UTC, so in this case we need to concern ourselves with no other time zones.
If you needed seconds rather than milliseconds, it’s tempting to divide by 1000. However, doing your own time conversions is a bad habit since the libraries already offers them, and using the appropriate library methods gives clearer, more explanatory and less error-prone code:
long secondsSinceEpoch = Instant.now().getEpochSecond();
System.out.println(secondsSinceEpoch);
1533458641
You said:
I just need to get the current time of GMT time zone…
Again taking your word:
OffsetDateTime currentTimeInUtc = OffsetDateTime.now(ZoneOffset.UTC);
System.out.println(currentTimeInUtc);
long millisecondsSinceEpoch = currentTimeInUtc.toInstant().toEpochMilli();
System.out.println(millisecondsSinceEpoch);
2018-08-05T08:44:01.719265Z
1533458641719
I know that GMT and UTC are not exactly the same, but for most applications they can be (and are) used interchangeably.
Can someone tell me (if) the above code is right?
When I ran your code just now, its output agreed with mine except the milliseconds were rounded down to whole thousands (whole seconds):
1533458641000
Your code has some issues, though:
You are using the old, long out-dated and poorly designed classes SimpleDateFormat, Date and TimeZone. The first in particular has a reputation for being troublesome. Instead we should use java.time, the modern Java date and time API.
Bug: In your format pattern string you are using lowercase hh for hour of day. hh is for hour within AM or PM, from 1 through 12, so will give you incorrect results at least half of the day. Uppercase HH is for hour of day.
Don’t use GMT-7 as a time zone. Use for example America/Los_Angeles. Of course select the time zone that makes sense for your situation. Edit: You said:
I just want to specify the timezone for sanjose. GMT-7 is refer to
sanjose current time.
I believe many places are called San Jose. If you mean San Jose, California, USA, you are going to modify your program to use GMT-8 every time California goes back to standard time and opposite when summer time (DST) begins?? Miserable idea. Use America/Los_Angeles and your program will work all year.
Since you ask for time in the GMT time zone, what are you using GMT-7 for at all?
There is no point that I can see in formatting your Date into a string and parsing it back. Even if you did it correctly, the only result you would get would be to lose your milliseconds since there are no milliseconds in your format (it only has second precision; this also explained the rounding down I observed).
Links
Oracle tutorial: Date Time explaining how to use java.time, the modern Java date and time API.
San Jose, California on Wikipedia
Why not use Calendar class?
public long getEpochTime(){
return Calendar.getInstance(TimeZone.getTimeZone("GMT-7")).getTime().getTime()/1000; //( milliseconds to seconds)
}
It'll return the current Date's Epoch/Unix Timestamp.
Based on Harald's Comment:
public static long getEpochTime(){
return Clock.system(TimeZone.getTimeZone("GMT-7").toZoneId() ).millis()/1000;
}
Here is a solution using the java.time API
ZonedDateTime zdt = LocalDateTime.now().atZone(ZoneId.of("GMT-7"));
long millis = zdt.toInstant().toEpochMilli();
I have 2 Date variables, Date1 and Date2.
I want to check if Date 1 fall on the same date as Date2 (but they are allowed to have different times).
How do i do this?
It looks like a really easy thing to do, but i'm struggling.
EDIT: I want to avoid external libraries and stuff
EDIT:
My orgional idea was to remove the hour, min, sec but those features are marked as depreciated in Java. So what should I use????
Although given answers based on date component parts of a java.util.Date are sufficient in many parts, I would stress the point that a java.util.Date is NOT a date but a kind of UNIX-timestamp measured in milliseconds. What is the consequence of that?
Date-only comparisons of Date-timestamps will depend on the time zone of the context. For example in UTC time zone the date-only comparison is straight-forward and will finally just compare year, month and day component, see other answers (I don't need to repeat).
But consider for example the case of Western Samoa crossing the international dateline in 2011. You can have valid timestamps of type java.util.Date, but if you consider their date parts in Samoa you can even get an invalid date (2011-12-30 never existed in Samoa locally) so a comparison of just the date part can fail. Furthermore, depending on the time zone the date component can generally differ from local date in UTC zone by one day, ahead or behind, in worst case there are even two days difference.
So following extension of solution is slightly more precise:
SimpleDateFormat fmt = new SimpleDateFormat("yyyyMMdd");
fmt.setTimeZone(...); // your time zone
return fmt.format(date1).equals(fmt.format(date2));
Similar extension also exists for the more programmatic approach to first convert the j.u.Date-timestamp into a java.util.GregorianCalendar, then setting the time zone and then compare the date components.
Why don't you simply compare the year, month and day? You can write your method for doing it something like:
private boolean isDateSame(Calendar c1, Calendar c2) {
return (c1.get(Calendar.YEAR) == c2.get(Calendar.YEAR) &&
c1.get(Calendar.MONTH) == c2.get(Calendar.MONTH) &&
c1.get(Calendar.DAY_OF_MONTH) == c2.get(Calendar.DAY_OF_MONTH));
}
Today = Span Of Time
While the other answers may be correct, I prefer the approach where we recognize that "today" is actually a span of time.
Because of anomalies such as Daylight Saving Time (DST), days vary in length, not always 24 hours long. Here in the United States, some days are 23 hours long, some 25.
Half-Open
Commonly in data-time work, we use the "Half-Open" strategy where the beginning of a span is inclusive and the ending is exclusive. So that means "today" spans from the first moment of today up to, but not including, the first moment of tomorrow.
Time Zones
Time zones are critical, as explained in the correct answer by Meno Hochschild. The first moment of a day depends on its time zone rules.
Joda-Time
The Joda-Time library has nice classes for handling spans of time: Period, Duration, and Interval.
DateTimeZone timeZone = DateTimeZone.forID( "Europe/Paris" );
DateTime now = new DateTime( timeZone );
Interval today = new Interval( now.withTimeAtStartOfDay(), now.plusDays(1).withTimeAtStartOfDay() );
DateTime dateTimeInQuestion = new DateTime( date ); // Convert java.util.Date.
boolean happensToday = today.contains( dateTimeInQuestion );
Benefits
This approach using a span of time has multiple benefits:
Avoids Daylight Saving Time (DST) issues
Lets you compare date-time values from other time zones
Flexible, so you can use the same kind of code for other spans (multiple days, months, etc.)
Gets your mind shifted away from calendar dates (a layered abstraction) and onto date-times as points on a flowing timeline (the underlying truth).
Java 8 has a new java.time package built-in. These new classes are modeled after Joda-Time but are entirely re-architected. This same kind of code can be written using java.time.
When you use the toString() method what do you get? Is it only the year/month/day or time too? If it is then you could simply compare the strings of the two objects. (date1.toString().equals(date2.toString()));
I am trying to run a report every Sunday at midnight that will include data from the previous Saturday at midnight, to 11:59:59 just prior to the report kicking off. Hence, if it were to get kicked off this coming Sunday (2/17), it would:
Execute at 2/17/2013 at midnight (or Monday morning, however you like to think of it)
Include data starting at 2/10/2013 12:00:00 AM (last Saturday midnight)
Include data up to 2/16/2013 11:59:59 PM (this Saturday night, just 1 second prior to the report firing)
I'm trying to obtain a startDateTime and endDateTime to encapsulate the time range, and want to use a JODA LocalDateTime to hold each value. I then need to format them into YYYYMMDD_HHmmss-formatted strings.
Here's my best attempt:
LocalDateTime rightNow = new LocalDateTime();
LocalDateTime startDateTime = rightNow.minusDays(7);
LocalDateTime endDateTime = rightNow.minusDays(1);
String startDateTimeFormatted = startDateTime.toString();
String endDateTimeFormatted = endDateTime.toString();
System.out.println(startDateTimeFormatted);
System.out.println(endDateTimeFormatted);
When I run this I get:
2013-02-06T12:10:27.411
2013-02-12T12:10:27.411
Note: since I'm running this code today (2/13/2013) the start/end dates are different then they would be on Sunday 2/17 (or any other Sunday), but its the time representation and the String formatting I'm really interested in here.
So I ask:
How to get startDateTime to represent (for this example - but I need the answer to be dynamic!) 2/10/2013 12:00:00 AM
How to get endDateTime to represent (for this example - but I need the answer to be dynamic!) 2/16/2013 11:59:59 PM
How to format both startDateTime and endDateTime to appear as 20130210_120000 and 20130216_115959 respectively?
Thanks in advance.
Okay, as mentioned before, I would strongly recommend using UTC as the time zone, and an exclusive end point. So, you can use:
private static final DateTimeFormatter FORMATTER =
DateTimeFormat.forPattern("yyyyMMdd'_'HHmmss")
.withLocale(Locale.US);
...
// I prefer to be explicit about using "the current time". I prefer to use
// an injectable dependency such as a Clock type, too...
DateTime now = new DateTime(System.currentTimeMillis(), DateTimeZone.UTC);
// Note: this *doesn't* ensure that it's the right day of the week.
// You'd need to think about that separately - it may be as simple as
// scheduling it appropriately... but bear your local time zone in mind!
DateTime end = now.withTimeAtStartOfDay();
DateTime start = end.minusDays(7);
String startText = FORMAT.print(start);
String endText = FORMAT.print(end);
Further note that this will use a 24-hour clock, so it would give 20130210_000000 and 20130217_000000 rather than using 120000 as the time. This is far more consistent and unambiguous. Given that it's always midnight though, you might want to just use yyyyMMdd and remove the time part entirely.
System.out.println(DateTime.now().toString("yyyy-MM-dd"));
the toString method accepts a formatting template, see: http://joda-time.sourceforge.net/apidocs/org/joda/time/format/DateTimeFormat.html
I have a report created in Jasper Reports which ONLY recognizes java.util.Date's (not Calendar or Gregorian, etc).
Is there a way to create a date 7 days prior to the current date?
Ideally, it would look something like this:
new Date(New Date() - 7)
UPDATE: I can't emphasize this enough: JasperReports DOES NOT RECOGNIZE Java Calendar objects.
From exactly now:
long DAY_IN_MS = 1000 * 60 * 60 * 24;
new Date(System.currentTimeMillis() - (7 * DAY_IN_MS))
From arbitrary Date date:
new Date(date.getTime() - (7 * DAY_IN_MS))
Edit: As pointed out in the other answers, does not account for daylight savings time, if that's a factor.
Just to clarify that limitation I was talking about:
For people affected by daylight savings time, if by 7 days earlier, you mean that if right now is 12pm noon on 14 Mar 2010, you want the calculation of 7 days earlier to result in 12pm on 7 Mar 2010, then be careful.
This solution finds the date/time exactly 24 hours * 7 days= 168 hours earlier.
However, some people are surprised when this solution finds that, for example, (14 Mar 2010 1:00pm) - 7 * DAY_IN_MS may return a result in(7 Mar 2010 12:00pm) where the wall-clock time in your timezone isn't the same between the 2 date/times (1pm vs 12pm). This is due to daylight savings time starting or ending that night and the "wall-clock time" losing or gaining an hour.
If DST isn't a factor for you or if you really do want (168 hours) exactly (regardless of the shift in wall-clock time), then this solution works fine.
Otherwise, you may need to compensate for when your 7 days earlier doesn't really mean exactly 168 hours (due to DST starting or ending within that timeframe).
Use Calendar's facility to create new Date objects using getTime():
import java.util.GregorianCalendar;
import java.util.Date;
Calendar cal = new GregorianCalendar();
cal.add(Calendar.DAY_OF_MONTH, -7);
Date sevenDaysAgo = cal.getTime();
try
Date sevenDay = new Date(System.currentTimeMillis() - 7L * 24 * 3600 * 1000));
Another way is to use Calendar but I don't like using it myself.
Since no one has mentioned TimeUnit yet:
new Date(System.currentTimeMillis() - TimeUnit.DAYS.toMillis(7))
Java 8 based solution:
new Date(
Instant.now().minus(7, ChronoUnit.DAYS)
.toEpochMilli()
)
Try this:
Calendar c = Calendar.getInstance();
c.add(Calendar.DAY_OF_MONTH, -7);
return c.getTime();
A determining "days" requires a time zone. A time zone defines when a "day" begins. A time zone includes rules for handling Daylight Saving Time and other anomalies. There is no magic to make time zones irrelevant. If you ignore the issue, the JVM's default time zone will be applied. This tends to lead to confusion and pain.
Avoid java.util.Date
The java.util.Date and .Calendar classes are notoriously troublesome. Avoid them. They are so bad that Sun/Oracle agreed to supplant them with the new java.time package in Java 8. Use either that or Joda-Time.
Joda-Time
Example code in Joda-Time 2.3.
DateTimeZone timeZone = DateTimeZone.forID( "Europe/Paris" ); // Specify or else the JVM's default will apply.
DateTime dateTime = new DateTime( new java.util.Date(), timeZone ); // Simulate passing a Date.
DateTime weekAgo = dateTime.minusDays( 7 );
First Moment Of Day
Or, you may want to adjust the time-of-day to the first moment of the day so as to capture an entire day's worth of time. Call the method withTimeAtStartOfDay. Keep in mind this is usually 00:00:00 but not always.
Avoid the "midnight" methods and classes in Joda-Time. They are based on a faulty concept and are now deprecated.
DateTime dateTimeStart = new DateTime( new java.util.Date(), timeZone ).withTimeAtStartOfDay(); // Not necessarily the time "00:00:00".
DateTime weekAgo = dateTime.minusDays( 7 ).withTimeAtStartOfDay();
Convert To/From j.u.Date
As seen above, to convert from java.util.Date to Joda-Time merely pass the Date object to constructor of DateTime. Understand that a j.u.Date has no time zone, a DateTime does. So assign the desired/appropriate time zone for deciding what "days" are and when they start.
To go the other way, DateTime to j.u.Date, simply call the toDate method.
java.util.Date date = dateTime.toDate();
I'm not sure when they added these, but JasperReports has their own set of "functions" that can manipulate dates. Here is an example that I haven't tested thoroughly:
DATE(YEAR(TODAY()), MONTH(TODAY()), DAY(TODAY()) - 7)
That builds a java.util.Date with the date set to 7 days from today. If you want to use a different "anchor" date, just replace TODAY() with whatever date you want to use.
You can try this,
Calendar c = Calendar.getInstance();
c.add(Calendar.DAY_OF_MONTH, -7);
System.out.println(new java.sql.Date(c.getTimeInMillis()));
Due to the heated discussion:
The question may not have a proper answer w/o a designated timezone.
below it is some code to work w/ the default (and hence deprecated) timezone that takes into account the default timezone daylight saving.
Date date= new Date();
date.setDate(date.getDate()-7);//date works as calendar w/ negatives
While the solution does work, it is exactly as bogus as in terms of assuming the timezone.
new Date(System.currentTimeMillis() - 10080*60000);//a week has 10080 minutes
Please, don't vote for the answer.
I'm doing it this way :
Date oneWeekAgo = DateUtils.addDays(DateUtils.truncate(new Date(), java.util.Calendar.DAY_OF_MONTH), -7);