How can I learn how many days passed from a specific date? - java

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 ;)

Related

Not gettin correct Days diff betweentwo dates of different year

I am using java code to find the days diff. between two dates let say '12/27/16' and '01/01/17'
Code is:
SimpleDateFormat format = new SimpleDateFormat("mm/dd/yy");
Date d1= format.parse("12/27/16");
Date d2=format.parse("01/01/17");
long diff = d1.getTime()-d2.getTime();
long diffDays= diff / (24*60*60*1000);
But when I print diffDays then i am getting 352 days rather 6 days
If you print d1, you'll see:
Wed Jan 27 00:12:00 CET 2016
That's definitely not what you put in. The reason is that your format string is wrong: m means minutes, not month. The correct format is "M/d/y".
And, as #nbokmans already noted, d1 - d2 is backwards and should be d2 - d1.
See also the documentation for SimpleDateFormat.
As #Thomas and #nbokmans answered, the dates are the wrong way round (but the code can be easily changed to ignore this). However, Java has a lot of convenience classes for dealing with times and dates that are not well known. I would replace the explicit calculation with one of the following:
SimpleDateFormat format = new SimpleDateFormat("MM/dd/yy");
Date d1 = format.parse("12/27/16");
Date d2 = format.parse("01/01/17");
long days1 = TimeUnit.MILLISECONDS.toDays(d2.getTime() - d1.getTime());
long days2 = Duration.between(d1.toInstant(), d2.toInstant()).abs().toDays();
long days3 = ChronoUnit.DAYS.between(d1.toInstant(), d2.toInstant());

Joda-Time - Number of seconds between two dates

My english is not perfect, but I hope you can understand me.
I try to get the difference in seconds between two unix timestamps, but it's only return 0.
That's my code
unixOnline = Long.valueOf(online);
unixOffline = Long.valueOf(offline);
DateTimeZone BERLIN = DateTimeZone.forID("Europe/Berlin");
DateTime dateTimeOnline = new DateTime(unixOnline * 1000L, BERLIN);
DateTime dateTimeOffline = new DateTime(unixOffline * 1000L, BERLIN);
int seconds = Seconds.secondsBetween(new LocalDate(dateTimeOnline), new LocalDate(dateTimeOffline)).getSeconds();
System.out.println("Seconds: " + seconds);
Edit:
Online Timestamp: 1457536522
Offline Timestamp: 1457536642
LocalDate has no time component, so if the times are on the same day, they're effectively turned into the same time. Instead, just diff the DateTimes as they are;
int hours = Hours.hoursBetween(dateTimeOnline, dateTimeOffline).getHours();
(or in your case, since the difference is only 2 minutes, you'll only see the result with Minutes or Seconds)
EDIT: Since the question seems to have nothing to do with the time zone BERLIN which is in the code, this answer is a bit over complicated. Instead, use krzydyn's answer if it's just a time diff between UTC times.
Since you already have timestamps in seconds it can be simple calculated by formula:
int hours = (t2-t1)/3600;
Or if you need fractions:
float hours = (t2-t1)/3600f;
Update: (maybe I got suggested by the answer :)
So to get time diff in seconds is even simpler:
long seconds = t2-t1;

how to find the total number of months between the two dates including extra days?

I have a requirement where I need to find out number of months between two dates including extra days.
example:
start date:01/01/2014
end date:21/02/2014
LocalDate startDate = new LocalDate(startDate1);
LocalDate endDate = new LocalDate(endDate1);
PeriodType monthDay =PeriodType.yearMonthDay().withYearsRemoved();
Period difference = new Period(startDate, endDate, monthDay);
int months = difference.getMonths();
int days = difference.getDays()
the out put I will get is:
months:1 days:20
but my requirement is I want get total months including that extra day.
like:1.66 months.
How to get this one in java?
In order to be able to say 1.66 months you need to define how long a month is. It's not always the same. If you assume that a month is 30 days long then you can solve this by using:
Date startDate = new SimpleDateFormat("dd/MM/yyyy").parse("01/01/2014");
Date endDate = new SimpleDateFormat("dd/MM/yyyy").parse("21/02/2014");
double result = (endDate.getTime() - startDate.getTime()) / (1000D*60*60*24*30);
This gives us 1.7 and if you divide with 31 you get 1.6451612903225807.
If you want a better (but not perfect) approximation of how long a month is you can try 365/12 which will give you 1.6767123287671233 but still this is not perfect because leap years have 366 days.
The problem though is not with the formula, but with the problem definition. Nobody in real life says "I'll be there in exactly 1.66 months" and nobody will ever ask you to convert 1.66 months in days.
This is my own answer, a variation on cherouvim's
final Date startDate = new GregorianCalendar (2014, 0, 1).getTime ();
final Date endDate = new GregorianCalendar (2014, 1, 21).getTime ();
System.out.println ((endDate.getTime () - startDate.getTime ()) / (float) (1000L * 60 * 60 * 24 * 30));

JAVA - Is it a bug in java.util.Calendar class or what?

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.

Time problem with this code

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 )));

Categories

Resources