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
Related
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
Something doesn't seem right and i just dont know how I can fix it.
I want to know the difference in days between 2 dates. Now I implemented a function, which calculates the differences from milliseconds to days for util.date objects
public long calculateNumberOfDays(Date from, Date to) {
return (to.getTime() - from.getTime()) / (1000*60*60*24);
}
My jUnit test told me, there was an error with this function, so I rewrote it using LocalDate and the ChronoUnit.DAYS.between function. It worked like a charm.
Wanting to know what the differences between those two functions were, I wrote this little test:
for(int numberDays = 1; numberDays<10; numberDays++){
LocalDate fromLD = LocalDate.now();
LocalDate toLD = fromLD.plusDays(numberDays);
Date fromD = Date.valueOf(fromLD);
Date toD = Date.valueOf(toLD);
long diffMS = toD.getTime() - fromD.getTime();
double diffDays = diffMS/(1000*60*60*24);
long numDaysDate = DAYS.between(fromLD, toLD);
System.out.println(numberDays+" = "+diffDays+"/"+numDaysDate);
}
It resulted in the following output:
1 = 1.0/1
2 = 2.0/2
3 = 3.0/3
4 = 4.0/4
5 = 4.0/5
6 = 5.0/6
7 = 6.0/7
8 = 7.0/8
9 = 8.0/9
Can someone explain to me, how this is possible? (1-4 it works, 5-9 util.date has lost a day)
Dates are hard. A java Date is a date and time, so when you set it to an actual date, it means midnight on that date.
Daylight savings time kicks in any day now (at least over here), so midnight on Monday will be 23 hours after midnight on Sunday.
Dividing integers rounds down, so 4 days and 23 hours is 4 days
Casting the result of an integer division to a double is too late; you need to cast either or both of the inputs:
double diffDays = diffMS/(1000*60*60*24);
4.0
double diffDays = diffMS/(1000.0*60*60*24);
4.958333...
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
In my program, I receive strings that define a time stamp in milliseconds. Now I need to convert this to a proper date. The solution I found looks something like this:
String aTime = "1365504203.0269";
double t = Double.parseDouble(aTime);
Date date = new Date((long)t*1000);
SimpleDateFormat dateFormatDDMMYYYY = new SimpleDateFormat("dd.MM.yyyy");
SimpleDateFormat dateFormatHHMMssSS = new SimpleDateFormat("HH:mm:ss:SS");
String day = new String(dateFormatHHMMssSS.format(date));
String hour = new String(dateFormatDDMMYYYY.format(date));
System.out.println("The Date: "+day);
System.out.println("The Time: "+hour);
Unfortunately, this removes the accuracy of milliseconds from the time stamp. (I'm not sure if the time is even that accurate as I can hardly think about it anymore.)
Has it gone lost due to double->long conversion, or has it never been there at all? Any way to workaround this problem?
The problem is in this statement:
Date date = new Date((long)t*1000);
It casts the double to a long first, thereby truncating the decimal places, and then multiplies by 1000, which just adds three zeros. Try this:
Date date = new Date((long)(t*1000.0));
It uses double as the data type for multiplication, which moves the decimal places into the integer part, and then makes the decimal place truncating long conversion.
Using 1000.0 instead of 1000 as the constant forces the constant to be of double type as well, adding an extra level of certainty that the multiplication will happen with doubles.
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.