Calculating difference between two java.sql.Timestamp shows negative value - java

I am calculating the difference between two timestamps which is in the following format
2013-07-22 05:24:24.77
I am using the following method to calculate the difference between two timestamps
DateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
Date resDate = sdf.parse(responseData.getTimestamp().toString());
Date reqDate = sdf.parse(requestData.getTimestamp().toString());
System.out.println("response-->"+responseData.getTimestamp());
System.out.println("request-->"+requestData.getTimestamp());
System.out.println("diff-->"+(resDate.getTime()-reqDate.getTime()));
The difference between two timestamps is negative in the following cases. For example
Response date : 2013-07-22 05:24:24.77
Request date : 2013-07-22 05:24:24.663
Result is :
diff-->-586
it should subtract something like this "770-663" instead it subtracting the timestamp as "77-663".
Can anyone please suggest what changes I should make or is there any other way to do it??
Thanks in advance

SSS in SimpleDateFormat means the number of milliseconds, not fractional second, that is for SimpleDateFormat 663 > 77. But Timestamp.toString formats timestamp in yyyy-mm-dd hh:mm:ss.fffffffff format, where fffffffff is fractional second. Usejava.sql.Timestamp.valueOf(str) for parsing what Timestamp.toString produces

Related

Compare time difference in hour from util Date

I want to compare time difference in hours. Based on current time and time I get from database.
DateFormat sdf = new SimpleDateFormat(“yyyy-MM-dd HH:mm:ss”);
Date date = new Date();
Logger.info(“current time is”,sdf.format(date));
// gives date in 2019-11-06 17:03:54
// dB gives following record
Date successDate = loader.getLastSuccess();
// gives date in 2019-10-31T:56:08.066+0000
Both formats are different how to get the time difference any suggestion experts
You can use the java-8 date API Duration to get the duration between both the dates
long hours = Duration.between(date1.toInstant(), date2.toInstant()).toHours();
Note : It can return negative value also here
the number of hours in the duration, may be negative
public int getHours() on util.Date is deprecated, so convert them to Instant and use Duration.between and also i will suggest to use java-8 Date API instead of older version Date
If you want difference in hours as double, you can do this;
Date your_date = loader.getLastSuccess();
Date currentDate = new Date();
double hourdifference = (currentDate.getTime() - your_date.getTime()) / 3600000.0;
You can get long or int, just change 3600000.0 to 3600000, and make the variable int or long

Java change double to Date

There is a problem when I tried to transform double to Date.
This is my code:
double itemDouble = 1370437809.00;
long itemLong = (long) (itemDouble * 1000);
Date itemDate = new Date(itemLong);
String itemDateStr = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SS").format(itemDate);
When the itemDouble is 1370437809.00, itemDateStr is 2013-06-05 21:10:09.00,
but when the itemDouble's decimal places is not zero, such as 1370437809.66, the itemDateStr is 2013-06-05 21:10:09.660. The formatted date string is not right.
How this happened?
According to your code, 1370437809.66 is a number of seconds since 1970. The decimal part represents 660 milliseconds. When you convert to a Date, you ask to display the milliseconds (the .SSS in the pattern). The result you get is correct.
you have 0.66*1000=660 that's correct

Compare same date using java

The date is selected by the user using a drop down for year, month and day. I have to compare the user entered date with today's date. Basically see if they are the same date. For example
the user entered 02/16/2012. And if today is 02/16/2012 then I have to display a message. How do I do it?
I tried using milliseconds but that gives out wrong results.
And what kind of object are you getting back? String, Calendar, Date? You can get that string and compare it, at least that you think you'll have problems with order YYYY MM DD /// DD MM YYY in that case I suggest to create a custom string based on your spec YYYYMMDD and then compare them.
Date d1 = new Date();
Date d2 = new Date();
String day1 = d1.getYear()+"/"+d1.getMonth()+"/"+d1.getDate();
String day2 = d2.getYear()+"/"+d2.getMonth()+"/"+d2.getDate();
if(day1.equals(day2)){
System.out.println("Same day");
}
Dates in java are moments in time, with a resolution of "to the millisecond". To compare two dates effectively, you need to first set both dates to the "same time" in hours, minutes, seconds, and milliseconds. All of the "setTime" methods in a java.util.Date are depricated, because they don't function correctly for the internationalization and localization concerns.
To "fix" this, a new class was introduced GregorianCalendar
GregorianCalendar cal1 = new GregorianCalendar(2012, 11, 17);
GregorianCalendar cal2 = new GregorianCalendar(2012, 11, 17);
return cal1.equals(cal2); // will return true
The reason that GregorianCalendar works is related to the hours, minutes, seconds, and milliseconds being initialized to zero in the year, month, day constructor. You can attempt to approximate such with java.util.Date by using deprecated methods like setHours(0); however, eventually this will fail due to a lack of setMillis(0). This means that to use the Date format, you need to grab the milliseconds and perform some integer math to set the milliseconds to zero.
date1.setHours(0);
date1.setMinutes(0);
date1.setSeconds(0);
date1.setTime((date1.getTime() / 1000L) * 1000L);
date2.setHours(0);
date2.setMinutes(0);
date2.setSeconds(0);
date2.setTime((date2.getTime() / 1000L) * 1000L);
return date1.equals(date2); // now should do a calendar date only match
Trust me, just use the Calendar / GregorianCalendar class, it's the way forward (until Java adopts something more sophisticated, like joda time.
There is two way you can do it. first one is format both the date in same date format or handle date in string format.
SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
String date1 = sdf.format(selectedDate);
String date2 = sdf.format(compareDate);
if(date1.equals(date2)){
}else{
}
Or
Calendar toDate = Calendar.getInstance();
Calendar nowDate = Calendar.getInstance();
toDate.set(<set-year>,<set-month>,<set-date->);
if(!toDate.before(nowDate))
//display your report
else
// don't display the report
Above answers are correct but consider using JodaTime - its much simpler and intuitive API.
You could set DateTime using with* methods and compare them.
Look at this answer

Time and Calendar

How do I add/subtract two time objects. I have two time objects (arrival and departure) in format of "yyyy/MMM/dd HH:mm:ss". I need to print the difference between departure and arrival time. I am generating time ad below:
public String getTime() {
Calendar currentDate = Calendar.getInstance();
SimpleDateFormat formatter = new SimpleDateFormat("yyyy/MMM/dd HH:mm:ss");
return formatter.format(currentDate.getTime());
}
Can I get time in mills and than format it when I needed to print ?
Take a look at Joda Time library.
You can easily subtract and add DateTime and find out interval easily :
// interval from start to end
DateTime start = new DateTime(2004, 12, 25, 0, 0, 0, 0);
DateTime end = new DateTime(2005, 1, 1, 0, 0, 0, 0);
Interval interval = new Interval(start, end);
something like this.....
public long getTimeDiff() throws Exception {
String arrival = "2011/Nov/10 13:15:24";
String departure = "2011/Jan/10 13:15:24";
SimpleDateFormat formatter = new SimpleDateFormat("yyyy/MMM/dd HH:mm:ss");
java.util.Date date1 = formatter.parse(arrival);
java.util.Date date2 = formatter.parse(departure);
return date2.getTime() - date1.getTime();
}
Convert them to date and then to long and subtract, that would give the time difference in milli seconds,
Date d1 = DateFormat.parse(time1);
Date d2 = DateFormat.parse(time2);
long diffInMilliSeconds = d1.getTime()-d2.getTime();
You can get time in milliseconds for both calendars using getTime method. When you can convert the result of subtraction to measure units that you need. If you're going to work with time/duration seriously when take a look at Joda library
Upd. You should call getTime twice. First object being returned is Date, when you call getTime on Date you get long value.
I would convert the two time/Date objects in milliseconds. Then i would subtract them (we are dealing with longs).
Then i would create a Date object from the resulting long value. After that you can construct a Calendar with Calendar.setDate(Date).
Regards!
Yes, start with your Dates and use getTime() to convert to milliseconds (or getTimeInMillis() for your Calendars). That give you long values you can subtract. That's the easy part.
Then you can convert these milliseconds into a readable format yourself. But it probably makes sense to use a packaged library to do it.
Some folks like the Joda library for these types of date calculations. I find Commons Lang is fantastic. It provides DateUtils which is useful if you find you want to perform calculations like rounding or truncating your dates to the nearest minute or hour etc. The part that will be most useful to you is the DurationFormatUtils class which gives you functions like formatDurationHMS to format into nice Hour:Minute:Second display and formatDurationWords to get text (fancy!) or other similar functions to easily format your milliseconds into a nicely human-readable format.

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.

Categories