Find difference between two time in java [duplicate] - java

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
How to convert Milliseconds to “X mins, x seconds” in Java?
Calculating the Difference Between Two Java Date Instances
I have a function like this:
public String setDateAndTime(int h, int m, int s,int amPm) {
TimeZone nst = TimeZone.getTimeZone("GMT+5:45");
Calendar calendar1 = new GregorianCalendar(nst);
Date currentTime1 = new Date();
calendar1.setTime(currentTime1);
calendar1.set(Calendar.HOUR, h);
calendar1.set(Calendar.MINUTE, m);
calendar1.set(Calendar.SECOND, s);
calendar1.set(Calendar.YEAR, calendar1.get(Calendar.YEAR));
calendar1.set(Calendar.MONTH, calendar1.get(Calendar.MONTH));
calendar1.set(Calendar.DAY_OF_MONTH, calendar1.get(Calendar.DAY_OF_MONTH));
calendar1.set(Calendar.AM_PM, amPm);
DateFormat formatter = new SimpleDateFormat("hh:mm:ss a");
String date = formatter.format(calendar1.getTime());
return date;
}
Through this function i created two dates(String)
String s1=setDateAndTime(12,00,00,1);//12:00:00 PM
String s2=setDateAndTime(3,15,45,0);//3:15:45 AM
Now how to find to find difference between s1 and s2, i also need the hours, minutes and second lefts, so that i can do further processing.

You can get time in milliseconds by calling getTime(). Then compare long values.
milliis/1000 gives seconds, millis/60/1000 gives minutes, millis/3600/1000 gives hours, etc.
You can also use 3rd party libraries like JodaTime but if you need this one-time Joda is too much.

Related

Is there a shortcut or a method that can return the difference between two dates? [duplicate]

This question already has answers here:
Calculating the difference between two Java date instances
(45 answers)
Closed 2 years ago.
After searching for a while about this topic i found 3 methods of Calendar class isBefore(), isAfter() And isAfter() but this methods only returns true or false . So my question here is there a method or a way that allowed us to compare two dates and print how much they differ .
Example :
Calendar date1 = new GregorianCalendar(2020,12,01);
Calendar date1 = new GregorianCalendar(2020,12,20);
We should return 29 days .
If youre not forced to use the Calendar class for this, you can get a duration easily with the LocalDate and Duration classes.
LocalDateTime now = LocalDateTime.of(2020, 12, 01);
LocalDateTime future = LocalDateTime.of(2020, 12, 20);
Duration duration = Duration.between(now, future);
long days = duration.toDays();

Java Date Comparison [duplicate]

This question already has answers here:
Comparing two java.util.Dates to see if they are in the same day
(14 answers)
How to know if a Date is within the same day of other date [duplicate]
(2 answers)
Closed 6 years ago.
According to Java API public boolean before(Date when)
true if and only if the instant of time represented by this Date
object is strictly earlier than the instant represented by when; false
otherwise.
Now I have to check if date input by user is greater than current date then only it will accept the input otherwise throw exception so i tried below
if(userInputDate.before(new Date())){
throw new Exception("Some Message");
}
But if both date are same then also it going to inside if statement .Do it mean it will calculate time and then check rather than comparing date? If yes how to resolve my issue ?
Can any one tell me how to add check for this?
The method before in the class Date is comparing the millisecond between the dates, so it's not comparing just the day, it is comparing the instant of time.
You could create a method to check if the dates are not in the same day and the first date is before the second one
public static boolean isBeforeDate(Date date1, Date date2) {
SimpleDateFormat fmt = new SimpleDateFormat("yyyyMMdd");
boolean areTheSameDay = fmt.format(date1).equals(fmt.format(date2));
return !areTheSameDay && date1.before(date2);
}
If you can use the new time api In Java8 instead of the old Date class, you can use the class LocalDate and the method compareTo:
boolean isBefore = myLocalDate.compareTo(myOtherLocalDate) < 0
All methods on java.util.Date that allow one to separate the time of day from the day of the year are deprecated. Therefore it is better to use java.util.Calendar. Additionally one should consider that there is typically one hour in each year that is in two days when summer time ends.
Here are two ways you can do it:
public static boolean isBeforeDay(Date date1, Date date2) {
// convert date1 to noon on the same day
Calendar day1 = Calendar.getInstance(TimeZone.getDefault());
day1.setTime(date1);
day1.set(Calendar.HOUR_OF_DAY, 12);
day1.set(Calendar.MINUTE, 0);
day1.set(Calendar.SECOND, 0);
day1.set(Calendar.MILLISECOND, 0);
// convert date2 to noon on the same day
Calendar day2 = Calendar.getInstance(TimeZone.getDefault());
day2.setTime(date2);
day2.set(Calendar.HOUR_OF_DAY, 12);
day2.set(Calendar.MINUTE, 0);
day2.set(Calendar.SECOND, 0);
day2.set(Calendar.MILLISECOND, 0);
return day1.before(day2);
}
public static boolean isBeforeDay(Date date1, Date date2) {
// get yyyymmdd value from date1
Calendar day1 = Calendar.getInstance(TimeZone.getDefault());
day1.setTime(date1);
int ymd1 = 10000*day1.get(Calendar.YEAR) + 100*day1.get(Calendar.MONTH) + day1.get(Calendar.DAY_OF_MONTH);
// get yyyymmdd value from date2
Calendar day2 = Calendar.getInstance(TimeZone.getDefault());
day2.setTime(date2);
int ymd2 = 10000*day2.get(Calendar.YEAR) + 100*day2.get(Calendar.MONTH) + day2.get(Calendar.DAY_OF_MONTH);
return ymd1 < ymd2;
}

Java date/calendar ignoring time zone [duplicate]

This question already has answers here:
Date and time conversion to some other Timezone in java
(11 answers)
Closed 8 years ago.
How to ignore timezone in dates? I mean I seted some jsf input with 8:54 with format HH:mm, and in setter I am getting 9:54, i Think that is because of time zone GMT+1. How to convert this date to ignore time zone? How to convert it when i dont know from which time zone I am using it.
code, setter of time picker input:
public void setDateTest(Date hmm){
if (hmm!=null){
int a = hmm.getHours();
int b = hmm.getMinutes();
Calendar cal = Calendar.getInstance();
cal.get(Calendar.ZONE_OFFSET);
cal.setTime(hmm);
int a2 = cal.get(Calendar.HOUR);
int c2 = cal.get(Calendar.HOUR_OF_DAY);
int b2 = cal.get(Calendar.MINUTE);
}
}
if you are using java.util.Calendar (probably you are), Hour index is in range between 0-11
http://docs.oracle.com/javase/7/docs/api/java/util/Calendar.html#HOUR
so if you are giving 8 for Calendar.HOUR, this is actually 9. This might be the cause. Just an opinion...

Convert String dates into Java Date objects [duplicate]

This question already has answers here:
Closed 11 years ago.
Possible Duplicates:
Calculating difference in dates in Java
How can I calculate a time span in Java and format the output?
Say you were given two dates as strings and they are in this format 8/11/11 9:16:36 PM how would I go about converting them to java Date objects so that I can then calculate the difference between two dates?
As long as both times are in GMT/UTC, you can do date1.getTime() - date2.getTime() and then divide the result by 86400000 to get number of days. The rest is probably pretty intuitive.
EDIT -- based on edited question
To convert Strings into dates, use the SimpleDateFormat class.
String yourDateString = "8/11/11 9:16:36 PM";
SimpleDateFormat format =
new SimpleDateFormat("MM/dd/yy HH:mm:ss a");
Date yourDate = format.parse(yourDateString);
The majority of Date's getters are deprecated, replaced with Calendar methods. Here's how you would do it
Date date1, date2; //initialized elsewhere
Calendar day1 = new Calendar();
day1.setTime(date1)
Calendar day2 = new Calendar();
day2.setTime(date2);
int yearDiff, monthDiff, dayDiff, hourDiff, minuteDiff, secondDiff;
yearDiff = Math.abs(day1.get(Calendar.YEAR)-day2.get(Calendar.YEAR));
monthDiff = Math.abs(day1.get(Calendar.MONTH)-day2.get(Calendar.MONTH));
dayDiff = Math.abs(day1.get(Calendar.DAY_OF_YEAR)-day2.get(Calendar.DAY_OF_YEAR));
hourDiff = Math.abs(day1.get(Calendar.HOUR_OF_DAY)-day2.get(Calendar.HOUR_OF_DAY));
minuteDiff = Math.abs(day1.get(Calendar.MINUTE)-day2.get(Calendar.MINUTE));
secondDiff = Math.abs(day1.get(Calendar.SECOND)-day2.get(Calendar.SECOND));
Then you can do whatever you like with those numbers.
define a SimpleDateFormat matching your format (the java doc is pretty straighforward), then use the parse method to get a the proper Date object, from which you can easily compute the difference between the two dates.
Once you have this difference, the best is probably to compute "manually" the number of days / hours / minutes / seconds, although it might be possible to again use a SimpleDateFormat (or some other formatting mechanism) to display the proper values in a generic way.

How to write a method that returns number (int) of days from provided day to the todays date?

Please help me to write a method that returns number (int) of days from a provided day to the todays date.
So let's say, I am providing into a method an int 110515 (for May 15, 2011). It should return 9 (inclusive or exclusive is not important to me).
If you can use Joda, this is super simple:
Days d = Days.daysBetween(startDate, endDate);
int days = d.getDays();
Of course you could combine these.
int days = Days.daysBetween(startDate, endDate).getDays();
Joda objects can go back and forth between the JDK's date class pretty easily.
For the first part, make a DateFormatter then parse the string based on it, like this:
DateTimeFormatter fmt = DateTimeFormat.forPattern("yyyyMMdd");
DateTime dt = fmt.parseDateTime(strInputDateTime);
(After turning the int into a string of course.)
Should dates in the future include the current day? Meaning if today is May 24th 2011, should 110529 result in 4 or 5?
public static long numberOfDays(final long date) throws ParseException {
final Calendar compare = Calendar.getInstance();
compare.setTime(new SimpleDateFormat("yyMMdd").parse(String.valueOf(date)));
final int dstOffset = compare.get(Calendar.DST_OFFSET);
final long currentTimeMillis = System.currentTimeMillis();
final long compareTimeInMillis = compare.getTimeInMillis();
long difference = 0;
if (currentTimeMillis >= compareTimeInMillis) {
difference = currentTimeMillis - compareTimeInMillis - dstOffset;
} else {
difference = compareTimeInMillis - currentTimeMillis + dstOffset;
}
return difference / (24 * 60 * 60 * 1000);
}
Since this seems like a homework question I will help you out. You will want to use Calendar.getTimeInMillis. Then you will want to create a constant that is NUMBER_OF_MILLIS_IN_DAY . From there you subtract the initialDate from the currentDate (both time in millis) and divide by the constant.

Categories