Finding difference between dates in java [duplicate] - java

This question already has answers here:
Calculating difference in dates in Java
(7 answers)
Closed 6 years ago.
I am new to java. I am having slight confusion regarding date arithmetic in java. I have following scenario, where I want to find differences between two dates :-
java.util.Date objDt1 = getDate1FromSrc1(); // I am obtaining it from src1
java.util.Date objDt2 = getDate2FromOtherSrc(); // I am getting dt2 by other way.
Now, I want to find difference between two dates and the output must be other date object.
So, I have written the following code :-
Calendar objCal1 = Calendar.getInstance();
Calendar objCal2 = Calendar.getInstance();
objCal1.setTime(objDt1);
objCal2.setTime(objDt2);
objCal1.add(Calendar.DAY_OF_MONTH, -objCal2.get(Calendar.DAY_OF_MONTH));
objCal1.add(Calendar.MONTH, -objCal2.get(Calendar.MONTH));
objCal1.add(Calendar.YEAR, -objCal2.get(Calendar.YEAR));
objCal1.add(Calendar.HOUR_OF_DAY, -objCal2.get(Calendar.HOUR_OF_DAY));
objCal1.add(Calendar.MINUTE, -objCal2.get(Calendar.MINUTE));
objCal1.add(Calendar.SECOND, -objCal2.get(Calendar.SECOND));
java.util.Date objDiff = objCal1.getTime();
But, I am getting some wierd results. Eg. If objDt1 is "02/22/2016 09:00:00" and objDt2 is "02/22/2016 11:00:00", then I am expecting objDiff to be "02:00:00" as output, which I am not getting.
Can you suggest me what's wrong I am doing here and what's the right way to approach this problem ?
Thanks in advance.

In order to find the difference between two dates you can simply convert it to long as follows:
java.util.Date objDt1 = getDate1FromSrc1();
java.util.Date objDt2 = getDate2FromOtherSrc();
long date1 = objDt1.getTime();
long date2 = objDt2.getTime();
System.out.println("Difference (In Seconds): " + (date2 - date1)/1000);
If you want this difference to be in HH:mm:ss format then you can do something like this:
public static void main (String[] args) throws Exception
{
SimpleDateFormat sf = new SimpleDateFormat("HH:mm:ss");
java.util.Date objDt1 = getDate1FromSrc1();
java.util.Date objDt2 = getDate2FromOtherSrc();
long date1 = objDt1.getTime();
long date2 = objDt2.getTime();
System.out.println("Difference: " + sf.format(new Date((date2 - date1)/1000)));
}

Related

How to compare two dates in Java by incrementing Date? [duplicate]

This question already has answers here:
How can I increment a date by one day in Java?
(32 answers)
How to compare dates in Java? [duplicate]
(11 answers)
Closed 2 years ago.
How to compare two dates in Java by incrementing Date?
String dt = "2008-01-01"; // Start date
String et="2008-01-10";
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
Calendar c = Calendar.getInstance();
Date startDate=sdf.parse(dt);
Date endDate=sdf.parse(et);
Date incDate;
// dt is now the new date
do
{
System.out.println("hey i am called.....");
c.setTime(sdf.parse(dt));
c.add(Calendar.DATE, 1); // number of days to add
dt = sdf.format(c.getTime());
System.out.println("Incremet Date"+dt);
incDate=sdf.parse(dt);
}
while(endDate.compareTo(incDate)>=0);
first you should start using the newer classes like #TomStroemer pointed out.
I think you want to get the number of days between the two dates ?
LocalDate startDate = LocalDate.parse("2008-01-01");
LocalDate endDate = LocalDate.parse("2008-01-10");
Period period = Period.between(startDate, endDate);
System.out.println(period.getDays());
Should print 8 because there are 8 days between. Haven't tested that code.
See the following docs:
Period: https://docs.oracle.com/javase/8/docs/api/java/time/Period.html
LocalDate: https://docs.oracle.com/javase/8/docs/api/java/time/LocalDate.html
And really provide more details.

Calculate Days Between Dates "JAVA" [duplicate]

This question already has answers here:
Calculating the difference between two Java date instances
(45 answers)
Closed 8 years ago.
i am making a university project assignment and i am trying to calculate the days between two dates, but so far i did not achieved anything.
The problem is:
I receive two strings in this format "NNNN#AAAA-MM-DD" and i need to check if the dates are alright and all of that. I already made the methods to do it and they are working. The problem is that i cant figure it out how to see the days between without the use of calendar method or date or any type of those ones.
Thanks ;)
you can use this method for convert the string in date:
public Date convertStringToDate(String dateString)
{
Date date = null;
Date formatteddate = null;
DateFormat df = new SimpleDateFormat("NNNN#yyyy-MM-dd");
try{
date = df.parse(dateString);
formatteddate = df.format(date);
}
catch ( Exception ex ){
return null;
}
return formatteddate;
}

how do i get the difference between two dates in days in java [duplicate]

This question already has answers here:
Difference in days between two dates in Java?
(19 answers)
Closed 8 years ago.
i am trying to get the difference between two dates. one of the dates was parsed from a string(dateEmployd) and the other date is the current date (currentDate). This is what i did to get the dates...
public static Date getActiveService(String DtEmplydString){
SimpleDateFormat ft = new SimpleDateFormat("yyyy-MM-dd");//formater for parsed String date
Date dateEmployd, currentDate,periodDifference = null;
try{
dateEmployd = ft.parse(DtEmplydString);
currentDate = new Date();
}catch(ParseException e){
JOptionPane.showMessageDialog(null, e);
}
return periodDifference;
}
Now, i am meant to return periodDifference but i dont know how i would find the difference betweent the two dates (dateEmployd and currentDate) and display it in years or days or a combination of both.
please guys much help is needed. thanks in advance...
Take a look at the jodatime library. They have functions like
DateTime dateEmployd = DateTimeFormat.forPattern("yyyy-MM-dd").parse(DtEmplydString);
Years.yearsBetween(dateEmployd, DateTime.now())
The same for Days.daysbetween, Seconds, Hours etc.
long diff = date2.getTime() - date1.getTime();
You could try out the Java.Calendar for date functions because Date is deprecated .
Here is an example with Cdate comparators
Calendar start = Calendar.getInstance();
start.setTime(from ( your initial Date object here ) );
Calendar end = Calendar.getInstance();
end.setTime(new Date());
int actualDays = start.compareTo(end);

How to get time on Android phone programmatically? [duplicate]

This question already has answers here:
How to get current time and date in Android
(42 answers)
Closed 8 years ago.
I am using this Java method here to get the current time:
final Date d = new Date();
d.getTime();
1390283202624
What I am getting a numeric figure of datatype long. What I need is the exact time in the format hh:mm:ss. And in the end I also have to perform arithmetic on the figure obtained.
Any clue? Also is this a reliable way of obtaining time on Android phone because I am getting a constant value here?
Date d = new Date();
SimpleDateFormat sdf = new SimpleDateFormat("hh:mm:ss");
String formattedDate = sdf.format(d);
System.out.println(formattedDate);
Calendar instance = Calendar.getInstance();
int hour = instance.get(Calendar.HOUR);
int minute = instance.get(Calendar.MINUTE);
int second = instance.get(Calendar.SECOND);
use:
SimpleDateFormat sdf=new SimpleDateFormat("hh:mm:ss");
String time=sdf.format(new Date());
Use Calendar class.
Calendar c = Calendar.getInstance();
int seconds = c.get(Calendar.SECOND);
See this question. Calendar class contain all desired information.

How to get readable time from currentTimeMillis() [duplicate]

This question already has answers here:
How to transform currentTimeMillis to a readable date format? [duplicate]
(2 answers)
Closed 9 years ago.
So below there's a simple way to get a readout from current time millis, but how do I get from my millisecond value to a readable time? Would I be just a stack of modulus that are dividing incrementally by 60? (exception being 100 milliseconds to a second)
Would I be right in thinking/doing that?
Thanks in advance for any help you can give
public class DisplayTime {
public static void main(String[] args) {
System.out.print("Current time in milliseconds = ");
System.out.println(System.currentTimeMillis());
}
}
You may try like this:-
long yourmilliseconds = 1119193190;
SimpleDateFormat sdf = new SimpleDateFormat("MMM dd,yyyy HH:mm");
Date resultdate = new Date(yourmilliseconds);
System.out.println(sdf.format(resultdate));
Use that value with a Calendar object
Calendar c = Calendar.getInstance();
c.setTimeInMillis(System.currentTimeMillis());
String date = c.get(Calendar.YEAR)+"-"+c.get(Calendar.MONTH)+"-"+c.get(Calendar.DAY_OF_MONTH);
String time = c.get(Calendar.HOUR_OF_DAY)+":"+c.get(Calendar.MINUTE)+":"+c.get(Calendar.SECOND);
System.out.println(date + " " + time);
Output:
2013-8-21 16:27:31
Note: c.getInstance() already holds the current datetime, so the second line is redundant. I added it to show how to set the time in millis to the Calendar object
System.out.println(new java.util.Date());
is the same as
System.out.println(new java.util.Date(System.currentTimeMillis()));
bothe represent the current time in a readable format

Categories

Resources