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.
I want to create a Date object, set its elapsed time to 10000, 100000, 1000000, 10000000, 100000000, 1000000000, 10000000000, and 100000000000 milliseconds, and display the date and time using the toString() method.
But I am not sure how to create a for loop that manages with the increasing milliseconds value?
This is what I have so far:
public class Date {
public static void main(String[] args) {
long i = 0;
java.util.Date date = new java.util.Date(i);
date.setTime(i);
for (i = 1000; i < 100000000000L; i *= 10) {
System.out.println("Time elapsed: " + i + " milliseconds");
}
System.out.println("Date and time: " + date.toString());
}
}
Just put your date and toString into the for loop
long i = 0;
java.util.Date date = new java.util.Date(i);
for (i = 1000; i < 100000000000L; i *= 10) {
date.setTime(i);
System.out.println("Time elapsed: " + i + " milliseconds");
System.out.println("Date and time: " + date.toString());
}
}
import java.util.Date; // 1
class FoobarTimeMachine {
public static void main(String[] args) {
Date date; // 2
for(long i = 1000l; i <= 100000000000l; i *= 10) { // 3
System.out.println("Time elapsed since epoch: " + i + " milliseconds");
date = new Date(i); // 4
System.out.println("Corresponding date: " + date); // 5
}
}
}
Comments:
We're importing java.util.Date so we can use it later as Date.
We're not initialising the date right now, it's not needed.
With <= so we can reach 100 000 000 000.
Here we are initialising the date.
someString + someObject => someString + someObject.toString()
you can do as :
public static void main(String[] args) {
long i = 0;
Date d=new Date(i);
for (i = 1000; i < 100000000000L; i *= 10) {
System.out.println("Time elapsed: " + i + " milliseconds");
d.setTime(i);
System.out.println("Date and time: " + d.toString());
}
}
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!
I am using TimeStamp class to convert seconds into Day,Hours,Minutes,Seconds. I used following code
public static void calculateTime(long seconds) {
int day = (int)TimeUnit.SECONDS.toDays(seconds);
long hours = TimeUnit.SECONDS.toHours(seconds) - TimeUnit.SECONDS.toHours(TimeUnit.SECONDS.toDays(seconds));
long minute = TimeUnit.SECONDS.toMinutes(seconds) - TimeUnit.SECONDS.toMinutes(TimeUnit.SECONDS.toHours(seconds));
long second = TimeUnit.SECONDS.toSeconds(seconds) - TimeUnit.SECONDS.toSeconds(TimeUnit.SECONDS.toMinutes(seconds));
System.out.println("Day " + day + " Hour " + hours + " Minute " + minute + " Seconds " + second);
}
But I am not getting right result.
For example when I called this method as calculateTime(3600) it gives me the result as Day 0 Hour 1 Minute 60 Seconds 3540 instead of Day 0 Hour 1 Minute 0 Seconds 0.
What is the wrong with my logic? Please help me.
It should be like
int day = (int)TimeUnit.SECONDS.toDays(seconds);
long hours = TimeUnit.SECONDS.toHours(seconds) - (day *24);
long minute = TimeUnit.SECONDS.toMinutes(seconds) - (TimeUnit.SECONDS.toHours(seconds)* 60);
long second = TimeUnit.SECONDS.toSeconds(seconds) - (TimeUnit.SECONDS.toMinutes(seconds) *60);
EDIT
Explanation:
Day calculation is correct, it does not require explanation.
TimeUnit.SECONDS.toHours(seconds) will give you direct conversion from seconds to hours without consideration for days you have already calculated. Minus the hours for days you already got i.e, day*24. You now got remaining hours.
Same for minute and second. You need to minus the already got hour and minutes respectively.
You can do like this to only use TimeUnit:
public static void calculateTime(long seconds) {
int day = (int) TimeUnit.SECONDS.toDays(seconds);
long hours = TimeUnit.SECONDS.toHours(seconds) -
TimeUnit.DAYS.toHours(day);
long minute = TimeUnit.SECONDS.toMinutes(seconds) -
TimeUnit.DAYS.toMinutes(day) -
TimeUnit.HOURS.toMinutes(hours);
long second = TimeUnit.SECONDS.toSeconds(seconds) -
TimeUnit.DAYS.toSeconds(day) -
TimeUnit.HOURS.toSeconds(hours) -
TimeUnit.MINUTES.toSeconds(minute);
System.out.println("Day " + day + " Hour " + hours + " Minute " + minute + " Seconds " + second);
}
or the slightly shorter but maybe not as intuitive
public static void calculateTime(long seconds) {
int day = (int) TimeUnit.SECONDS.toDays(seconds);
long hours = TimeUnit.SECONDS.toHours(seconds) -
TimeUnit.DAYS.toHours(day);
long minute = TimeUnit.SECONDS.toMinutes(seconds) -
TimeUnit.HOURS.toMinutes(TimeUnit.SECONDS.toHours(seconds));
long second = TimeUnit.SECONDS.toSeconds(seconds) -
TimeUnit.MINUTES.toSeconds(TimeUnit.SECONDS.toMinutes(seconds));
System.out.println("Day " + day + " Hour " + hours + " Minute " + minute + " Seconds " + second);
}
Simple method:
public static void calculateTime(long seconds) {
long sec = seconds % 60;
long minutes = seconds % 3600 / 60;
long hours = seconds % 86400 / 3600;
long days = seconds / 86400;
System.out.println("Day " + days + " Hour " + hours + " Minute " + minutes + " Seconds " + sec);
}
Here is a code i created : (For 3600 seconds it shows "Days:0 Hours:1 Minutes:0 Seconds:0")
public class TimeConvert
{
public static void main(String[] args)
{
int fsec,d,h,m,s,temp=0,i;
fsec=3600;
//For Days
if(fsec>=86400)
{
temp=fsec/86400;
d=temp;
for(i=1;i<=temp;i++)
{
fsec-=86400;
}
}
else
{
d=0;
}
//For Hours
if(fsec>=3600)
{
temp=fsec/3600;
h=temp;
for(i=1;i<=temp;i++)
{
fsec-=3600;
}
}
else
{
h=0;
}
//For Minutes
if(fsec>=60)
{
temp=fsec/60;
m=temp;
for(i=1;i<=temp;i++)
{
fsec-=60;
}
}
else
{
m=0;
}
//For Seconds
if(fsec>=1)
{
s=fsec;
}
else
{
s=0;
}
System.out.println("Days:"+d+" Hours:"+h+" Minutes:"+m+" Seconds:"+s);
}
}
Hope it answers your question.
Late but helpful
get time in the format 00:00:00
/**
* The time in format.
*
* in The Format of 00:00:00
*/
public String getTimeInFormat(long _SECONDS)
{
if(TimeUnit.SECONDS.toHours(_SECONDS)>0)
{
return String.format("%02d:%02d:%02d",
TimeUnit.SECONDS.toHours(_SECONDS),
TimeUnit.SECONDS.toMinutes(_SECONDS) -
TimeUnit.HOURS.toMinutes(TimeUnit.SECONDS.toHours(_SECONDS)),
TimeUnit.SECONDS.toSeconds(_SECONDS) -
TimeUnit.MINUTES.toSeconds(TimeUnit.SECONDS.toMinutes(_SECONDS)));
}
else {
return String.format("%02d:%02d",
TimeUnit.SECONDS.toMinutes(_SECONDS) -
TimeUnit.HOURS.toMinutes(TimeUnit.SECONDS.toHours(_SECONDS)),
TimeUnit.SECONDS.toSeconds(_SECONDS) -
TimeUnit.MINUTES.toSeconds(TimeUnit.SECONDS.toMinutes(_SECONDS)));
}
}
Try this
public static void calculateTime(long seconds) {
int day = (int)TimeUnit.SECONDS.toDays(seconds);
long hours = TimeUnit.SECONDS.toHours(seconds) ;
long tempSec = seconds - (TimeUnit.HOURS.toSeconds(hours) );
System.out.println("after hours calculation "+ tempSec);
long minute = TimeUnit.SECONDS.toMinutes(tempSec);
if(tempSec > TimeUnit.MINUTES.toSeconds(minute)){
tempSec = tempSec - (TimeUnit.MINUTES.toSeconds(minute) );
}else{
tempSec = TimeUnit.MINUTES.toSeconds(minute) - tempSec;
}
System.out.println("after min calculation "+ tempSec);
long second = TimeUnit.SECONDS.toSeconds(tempSec) ;
System.out.println("Day " + day + " Hour " + hours + " Minute " + minute + " Seconds " + second);
}
This is my code:
public static String secondsToString(TimeUnit greatestUnit, long sourceDuration, TimeUnit sourceUnit) {
int ordinal = greatestUnit.ordinal();
if(ordinal<=sourceUnit.ordinal())
return String.format("%02d", sourceDuration);
final long greatestDuration = greatestUnit.convert(sourceDuration, sourceUnit);
final long rest = sourceDuration - sourceUnit.convert(greatestDuration, greatestUnit);
return String.format("%02d:", greatestDuration) + secondsToString(TimeUnit.values()[--ordinal], rest, sourceUnit);
}
or by loop
public static String secondsToStringByLoop(TimeUnit greatestUnit, long sourceDuration, TimeUnit sourceUnit) {
final StringBuffer sb = new StringBuffer();
int ordinal = greatestUnit.ordinal();
while(true){
if(ordinal<=sourceUnit.ordinal()) {
sb.append(String.format("%02d", sourceDuration));
break;
}
final long greatestDuration = greatestUnit.convert(sourceDuration, sourceUnit);
// if(greatestDuration>0 || sb.length()>0)
sb.append(String.format("%02d:", greatestDuration));
sourceDuration -= sourceUnit.convert(greatestDuration, greatestUnit);
greatestUnit = TimeUnit.values()[--ordinal];
};
return sb.toString();
}
usage example:
String str = secondsToString(TimeUnit.DAYS, 1000, TimeUnit.SECONDS);
function returns: "00:00:16:40" (days:hours:minutes:seconds)
str = UnitsConverter.secondsToString(TimeUnit.DAYS, 1000, TimeUnit.MINUTES);
returns: "00:16:40" (days:hours:minutes)
str = UnitsConverter.secondsToString(TimeUnit.MINUTES, 1000, TimeUnit.SECONDS);
returns: "16:40" (minutes:seconds)
public static void timeCalculator(){
Scanner input = new Scanner(System.in);
System.out.print("Enter length of time in seconds: ");
int n = input.nextInt();
int nDay = n/86400;
int nHours = (n%86400)/3600;
int nMin = ((n%86400)%3600) /60;
int nSec =(((n%86400)%3600)%60);
System.out.println();
System.out.print("That is "+ nDay+ " day(s),"+nHours+" hour(s), "+nMin+" minute(s), and "+nSec+" second(s). ");
}
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