Calculating difference in days between dates - java

In my code the difference between dates is wrong, because it should be 38 days instead of 8 days. How can I fix?
package random04diferencadata;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
public class Random04DiferencaData {
/**
* http://www.guj.com.br/java/9440-diferenca-entre-datas
*/
public static void main(String[] args) {
SimpleDateFormat sdf = new SimpleDateFormat("hh:mm dd/mm/yyyy");
try {
Date date1 = sdf.parse("00:00 02/11/2012");
Date date2 = sdf.parse("10:23 10/12/2012");
long differenceMilliSeconds = date2.getTime() - date1.getTime();
System.out.println("diferenca em milisegundos: " + differenceMilliSeconds);
System.out.println("diferenca em segundos: " + (differenceMilliSeconds / 1000));
System.out.println("diferenca em minutos: " + (differenceMilliSeconds / 1000 / 60));
System.out.println("diferenca em horas: " + (differenceMilliSeconds / 1000 / 60 / 60));
System.out.println("diferenca em dias: " + (differenceMilliSeconds / 1000 / 60 / 60 / 24));
} catch (ParseException e) {
e.printStackTrace();
}
}
}

The problem is in the SimpleDateFormat variable. Months are represented by Capital M.
Try change to:
SimpleDateFormat sdf = new SimpleDateFormat("hh:mm dd/MM/yyyy");
For more, see this javadoc.
Edited:
And here is the code if you want to print the difference the way you commented:
SimpleDateFormat sdf = new SimpleDateFormat("hh:mm dd/MM/yyyy");
try {
Date date1 = sdf.parse("00:00 02/11/2012");
Date date2 = sdf.parse("10:23 10/12/2012");
long differenceMilliSeconds = date2.getTime() - date1.getTime();
long days = differenceMilliSeconds / 1000 / 60 / 60 / 24;
long hours = (differenceMilliSeconds % ( 1000 * 60 * 60 * 24)) / 1000 / 60 / 60;
long minutes = (differenceMilliSeconds % ( 1000 * 60 * 60)) / 1000 / 60;
System.out.println(days+" days, " + hours + " hours, " + minutes + " minutes.");
} catch (ParseException e) {
e.printStackTrace();
}
Hope this help you!

Related

Calculate how long has passed Date java

I have a function:
public String getTimePast(Date d) {
//insertcodehere
}
That takes in a Date of a message and must return how much time has past based on the current time in specific format. For example if it has just been posted it will say "Now"
If it has been 4 minutes it will say "4min"
If it has been 23hrs it will say "23hrs"
Etc
Below is how I tried to do it with no luck! How am I able to do this? Thank you!
public String getTimePast(Date d) {
Calendar c = Calendar.getInstance();
int hr = c.get(Calendar.HOUR_OF_DAY);
int min = c.get(Calendar.MINUTE);
int day = c.get(Calendar.DAY_OF_MONTH);
int month = c.get(Calendar.MONTH);
int year = c.get(Calendar.YEAR);
if (year == d.getYear()) {
if (month == d.getMonth()) {
if (day == d.getDay()) {
if (hr == d.getHours()) {
if (min == d.getMinutes()) {
return "Now";
} else {
return min - d.getMinutes() + "m";
}
} else {
return hr - d.getHours() + "hr";
}
} else {
return day - d.getDay() + "d";
}
} else {
return month - d.getMonth() + "m";
}
} else {
return year - d.getYear() + "y";
}
}
How about using another Calendar Object as simply finding the difference
Calendar now = Calendar.getInstance();
Calendar start = Calendar.getInstance();
start.setTime (d);
long milliseconds1 = start.getTimeInMillis();
long milliseconds2 = now.getTimeInMillis();
long diff = milliseconds2 - milliseconds1;
long diffSeconds = diff / 1000;
long diffMinutes = diff / (60 * 1000);
long diffHours = diff / (60 * 60 * 1000);
long diffDays = diff / (24 * 60 * 60 * 1000);
System.out.println("\nThe Date Different Example");
System.out.println("Time in milliseconds: " + diff
+ " milliseconds.");
System.out.println("Time in seconds: " + diffSeconds
+ " seconds.");
System.out.println("Time in minutes: " + diffMinutes
+ " minutes.");
System.out.println("Time in hours: " + diffHours
+ " hours.");
System.out.println("Time in days: " + diffDays
+ " days.");
}
see http://www.roseindia.net/java/beginners/DateDifferent.shtml
You can use java.util.concurrent.TimeUnit
long diff = c.getTimeInMillis() - d.getTime();
long minutes = TimeUnit.MILLISECONDS.toMinutes(diff);
long hours = TimeUnit.MILLISECONDS.toHours(diff);
//(...)
and them check for values, like:
if (minutes > 60) {
if (hours > 24) {
// print days
} else {
// print hours
}
} else {
// print minutes
}
The easiest and most correct way to do this in Android is to use one of the functions in DateUtils, such as one of the variants of getRelativeTimeSpanString(). Which one to use is up to your requirements. This should be preferred because it will format the string according to the current locale, so it should work in any language supported by the device.

I am getting this error when I run the below java code

I'm getting this error when I run the below java code
Exception in thread "main" java.lang.Error: Unresolved compilation
problem: at my.time.main(time.java:9)
package my;
package com.mkyong.date;
import java.text.SimpleDateFormat;
import java.util.Date;
public class time {
public static void main(String[] args) {
String dateStart = "01/14/2012 09:29:58";
String dateStop = "01/15/2012 10:31:48";
//HH converts hour in 24 hours format (0-23), day calculation
SimpleDateFormat format = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss");
Date d1 = null;
Date d2 = null;
try {
d1 = format.parse(dateStart);
d2 = format.parse(dateStop);
//in milliseconds
long diff = d2.getTime() - d1.getTime();
long diffSeconds = diff / 1000 % 60;
long diffMinutes = diff / (60 * 1000) % 60;
long diffHours = diff / (60 * 60 * 1000) % 24;
long diffDays = diff / (24 * 60 * 60 * 1000);
System.out.print(diffDays + " days, ");
System.out.print(diffHours + " hours, ");
System.out.print(diffMinutes + " minutes, ");
System.out.print(diffSeconds + " seconds.");
} catch (Exception e) {
e.printStackTrace();
}
}
}
You set packagetwo times:
package my;
package com.mkyong.date;
It is only allowed one time. You should set your package to match your classes path.
Try to set the package my and import the class date:
package my;
import com.mkyong.date;

Java timeformat and time duration

Output I need is this:
Time in: 07:00 AM
Time out: 11:30 PM
Time duration: 16 hours and 30 minutes
User needs to enter in time in and time out, How do I do it? I searched and it seems that I need DateFormat hh:mm: a but I don't know how to use it. Help please. thanks.
DateFormat dateFormat = new SimpleDateFormat("hh:mm a");
long timeIn = dateFormat.parse("07:00 AM").getTime();
long timeOut = dateFormat.parse("11:30 PM").getTime();
long duration = (timeOut - timeIn) / 1000 / 60; // in minutes
long hours = duration / 60;
long minutes = duration % 60;
System.out.println("Time duration: " + hours + " hours and " + minutes + " minutes");
Prints:
Time duration: 16 hours and 30 minutes
Hi you can try something like this
public String timeDifference(String timeIn,String timeOut){
DateFormat dateFormat=new SimpleDateFormat("hh:mm a");
String result;
Date d=dateFormat.parse("08:14 AM"); //First input time in
Date d1=dateFormat.parse("09:00 PM"); //second input time out
long min=TimeUnit.MINUTES.convert(d1.getTime()-d.getTime(),TimeUnit.MILLISECONDS);
System.out.println(min);
if(min>=60){
long hrs=min/60;
result=String.valueOf(min/60)+" hours "+String.valueOf(min%60)+" minutes";
}
else
result=min+" minutes";
System.out.println(result);
return result;
}
You can trying something like this:
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
public class TimeTracker {
static Date getTimeIn() {
//There you must to use your specific Time In getting from user
//It's just example
Calendar calendarIn = Calendar.getInstance();
calendarIn.set(Calendar.HOUR_OF_DAY, 7);
calendarIn.set(Calendar.MINUTE, 00);
calendarIn.set(Calendar.SECOND, 0);
calendarIn.set(Calendar.MILLISECOND, 0 );
return calendarIn.getTime();
}
static Date getTimeOut() {
//There you must to use your specific Time In getting from user
//It's just example
Calendar calendarOut = Calendar.getInstance();
calendarOut.set(Calendar.HOUR_OF_DAY, 23);
calendarOut.set(Calendar.MINUTE, 30);
calendarOut.set(Calendar.SECOND, 0);
calendarOut.set(Calendar.MILLISECOND, 0);
return calendarOut.getTime();
}
public static void main(String[] args) throws InterruptedException {
DateFormat formatterTime = new SimpleDateFormat("hh:mm a");
long timeDuration = getTimeOut().getTime() - getTimeIn().getTime();
System.out.println("Time in: " + formatterTime.format(getTimeIn()));
System.out.println("Time out: " + formatterTime.format(getTimeOut()));
System.out.println("Time duration: " +
((timeDuration / (1000*60*60)) % 24)
+ " hours and " +
((timeDuration / (1000*60)) % 60) + " minutes");
}
}
Output is:
Time in: 07:00 AM
Time out: 11:30 PM
Time duration: 16 hours and 30 minutes

java.text.ParseException: Unparseable date: "11/11/2014"

I am trying to get the difference betweek to dates
String start_date, end_date;
System.out.println("Date Format: MM/DD/YYYY hh:mm:ss (24-hour format)");
System.out.print("Start Date and Time: ");
start_date = cin.next();
System.out.print("End Date and Time: ");
end_date = cin2.next();
SimpleDateFormat date_format = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss");
Date date1 = null, date2 = null;
try
{
date1 = date_format.parse(start_date);
date2 = date_format.parse(end_date);long diff = date1.getTime() - date2.getTime();
long diffSeconds = diff / 1000 % 60;
long diffMinutes = diff / (60 * 1000) % 60;
long diffHours = diff / (60 * 60 * 1000) % 24;
long diffDays = diff / (24 * 60 * 60 * 1000);
System.out.print(diffDays + " days, ");
System.out.print(diffHours + " hours, ");
System.out.print(diffMinutes + " minutes, ");
System.out.print(diffSeconds + " seconds.");
}
catch(Exception ex)
{
System.out.println(ex);
}
I keep on getting this error
Date Format: MM/DD/YYYY hh:mm:ss (24-hour format)
Start Date and Time: 11/11/2014 11:11:11
End Date and Time: 11/21/2014 11:11:11
java.text.ParseException: Unparseable date: "11/11/2014"
please help me
Notice your output
Start Date and Time: 11/11/2014 11:11:11
...
java.text.ParseException: Unparseable date: "11/11/2014"
You entered
11/11/2014 11:11:11
but only tried to parse
11/11/2014
Scanner#next() used here
start_date = cin.next();
tokenizes on whitespace (by default). Use Scanner#nextLine() to get the full line.

How to calculate the number of years in spring framework java [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
How do I calculate someone's age in Java?
I'm creating an application in spring framework which calculates the age after a user enters their birthdate to a UI. So far my getAge bean has the gets and sets, but how do I right the calculation method syntatically?
import java.util.*;
public class ageBean {
Date birthdate;
public Date getBirthday(){
return birthdate;
}
public void setBirthdate(Date birthdate){
this.birthdate=birthdate;
}
//method goes here
}
There is nothing with Spring . if you want to calculate current age,
long diff = new Date().getTime() - birthdate.getTime(); // current date - b'day
long diffSeconds = diff / 1000;
long diffMinutes = diff / (60 * 1000);
long diffHours = diff / (60 * 60 * 1000);
System.out.println("Time in seconds: " + diffSeconds + " seconds.");
System.out.println("Time in minutes: " + diffMinutes + " minutes.");
System.out.println("Time in hours: " + diffHours + " hours.");
Use java.util.Calendar to ensure leap years, varying numbers of days in month etc. are accounted for,
int thisYear = Calendar.getInstance().get(Calendar.YEAR);
Calendar birthdateCalendar = Calendar.getInstance();
birthdateCalendar.setTime(birthdate);
int birthYear = birthdateCalendar.get(Calendar.YEAR);
int yearsSinceBirth = thisYear - birthYear;
You can try this piece of code by replacing date1 with your birthdate,
Date date= new Date(System.currentTimeMillis());
date.setYear(date.getYear()+1900);
// this is done as currentTimeMillis returns the time elapsed from 1 Jan 1970s
Date date1=new Date(2000,10,15);
long timegap =date.getTime()-date1.getTime();
long milliSecsInAYear = 31536000000L;
System.out.println(timegap/milliSecsInAYear+"years" +((date.getTime()-date1.getTime())%milliSecsInAYear)/(milliSecsInAYear/365)+"days" );
note : I have taken a year as having 365 days

Categories