How to get the time difference of different timezone? - java

I am trying to get the difference between the current time and the time which is stored in DB.
I tried below code but its not giving the correct result since java.lang.System.currentTimeMillis() returns
UTC time whereas we save date to our application in EST format.
Code :
java.lang.System.currentTimeMillis() - emp.getModifiedDate()
Could you please suggest me a correct way to do it ?It will be very helpful for me
Thanks

System.currentTimeMillis() returns the number of milliseconds since January 1, 1970 UTC. It is time-zone agnostic.
If you are storing the time in the database as millis then simply subtracting the two numbers will give you the correct difference.
If you are storing the time in some other way (e.g. as a String), you can parse it (e.g. with SimpleDateFormat) to take into account the time zone and then obtain a Date from which you can obtain the millis.

Hope this helps! This will give you difference in no of days.
Date date1 = new Date();
long diff = date1.getTime() - emp.getModifiedDate().getTime();
System.out.println((int) (diff) / (1000 * 60 * 60 * 24)));
For more read this

Related

Simple date format giving wrong time

I have a time in milliseconds: 1618274313.
When I convert it to time using this website: https://www.epochconverter.com/, I am getting 6:08:33 AM.
But when I use SimpleDateFormat, I am getting something different:
SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss", Locale.getDefault());
System.out.println(sdf.format(new Date(1618274313)));
I am getting output as 23:01:14.
What is the issue in my code?
In your example, you are using time 1618274313 and you are assuming that it is in milliseconds. However, when I entered the same time on https://www.epochconverter.com/, I got below results:
Please notice the site mentions: Assuming that this timestamp is in seconds.
Now if we use that number multiplied by 1000 (1618274313000) as the input so that the site considers it in milliseconds, we get below results:
Please notice the site now mentions: Assuming that this timestamp is in milliseconds.
Now, when you will use 1618274313000 (correct time in milliseconds) in Java with SimpleDateFormat, you should get your expected result (instead of 23:01:14):
SimpleDateFormat sdf=new SimpleDateFormat("HH:mm:ss", Locale.getDefault());
System.out.println(sdf.format(new Date(1618274313000)));
use Instant.ofEpochSecond
long test_timestamp = 1618274313L;
LocalDateTime triggerTime =
LocalDateTime.ofInstant(Instant.ofEpochSecond(test_timestamp),
TimeZone.getDefault().toZoneId());
System.out.println(triggerTime);
it prints output as 2021-04-13T06:08:33
Assuming it is in milliseconds as you say, all you know for certain is that you have a specific duration.
Duration d = Duration.ofMillis(1618274313);
System.out.println(d);
Prints
PT449H31M14.313S
Which says it is 449 hours, 31 minutes and 14.313 seconds of duration. Without knowing the epoch of this duration and any applicable zone offsets, it is not really possible to ascertain the specific date/time it represents. I could make lots of assumptions and provide results based on that, but more information from you would be helpful.
java.time
As Viral Lalakia already spotted, the epoch converter that you linked to, explicitly said that it assumed that the number was seconds (not milliseconds) since the epoch. The following makes the same assumption in Java. I recommend that you use java.time, the modern Java date and time API.
ZoneId zone = ZoneId.of("Asia/Kolkata");
long unixTimestamp = 1_618_274_313;
Instant when = Instant.ofEpochSecond(unixTimestamp);
ZonedDateTime dateTime = when.atZone(zone);
System.out.println(dateTime);
System.out.println(dateTime.format(DateTimeFormatter.ISO_LOCAL_TIME));
Output is:
2021-04-13T06:08:33+05:30[Asia/Kolkata]
06:08:33
This agrees with the 6:08:33 AM that you got from the converter. And the date is today’s date. A coincidence?
If the number is indeed milliseconds (which I honestly doubt), just use Instant.ofEpochMill() instead of Instant.ofEpochSecond().
Instant when = Instant.ofEpochMilli(unixTimestamp);
1970-01-19T23:01:14.313+05:30[Asia/Kolkata]
23:01:14.313
This in turn agrees with the result you got in Java (except that the milliseconds are also printed).

JODA DateTime provide a correct date and time as per daylight saving approach? or we need to add/subtract difference hour count from date [duplicate]

just to verify this: I have this lame and brain dead method to calculate the time zone offset for my current location. I wonder if I need to adjust it when Day Light Saving time comes into question (currently we have Winter Time at my location, CET time zone, so it's hard to verify).
// The local time zone's offset
private int getLocalOffset() {
DateTimeZone defaultZone = DateTimeZone.getDefault();
return defaultZone.getOffset(null) / 1000 / 60 / 60;
}
Thanks for any hint.
Time zones and Daylight Saving Time are a nightmare. You certainly shouldn't take on this task yourself. Let Joda-Time do the heavy lifting.
See this answer to similar question, Using Joda time to get UTC offset for a given date and timezone. The class DateTimeZone offers a getOffset() method.
Example source code in Joda-Time 2.3 in Java 7…
// © 2013 Basil Bourque. This source code may be used freely forever by anyone taking full responsibility for doing so.
org.joda.time.DateTimeZone californiaTimeZone = org.joda.time.DateTimeZone.forID("America/Los_Angeles");
org.joda.time.DateTime now = new org.joda.time.DateTime(californiaTimeZone);
int millisecondOffsetToAddToUtcToGetLocalTime = californiaTimeZone.getOffset( now );
System.out.println( "millisecondOffsetToAddToUtcToGetLocalTime: " + millisecondOffsetToAddToUtcToGetLocalTime );
// Note the casting to doubles to avoid integer truncation. Time zone offsets are NOT always whole hours.
System.out.println( "Offset in decimal hours: " + (double)millisecondOffsetToAddToUtcToGetLocalTime / 1000d / 60d / 60d );
When run at 2013-11-20T01:03:56.464-08:00…
millisecondOffsetToAddToUtcToGetLocalTime: -28800000
millisecondOffsetToAddToUtcToGetLocalTime in hours: -8.0
IMPORTANT That number format -8.0 is incorrect for an offset. Must be either:
-08:00 with the colon and double digits (padded with leading zero).
-08 with leading zero.
Normally, Joda time will take care of DST by itself, so you don't have to worry about it. However, I notice that you are passing null to getOffset(). Given that the time zone offset depends on the date, you really should be passing the date/time at which you are calculating the offset, or you're going to get wrong results.
Also as mentionned in my previous comment: Be aware that some timezones have an offset that isn't a whole number of hours. India for example is at GMT +5:30
Yes, that's fine. To verify that it is correct - instead of passing null pass in a DateTime object to DateTimeZone.getOffset - set the datetime to sometime in summer when you know DST is in effect - you should see the offset value change.

Get time difference java.sql.Time

I'm trying to get the time differente between two Time vars like this
long timeDiffLong = hFim.getTime() - hInic.getTime();
Time timeDiff = new Time(timeDiffLong);
The output is comming something like this
hFim = 17:30:00
hInic = 17:00:00
timeDiff = 20:30:00
instead of just showing 00:30:00 i always get 20h plus the result
If you use Java 8, you can do:
LocalTime from = hFim.toLocalTime();
LocalTime to = hInic.toLocalTime();
Duration d = Duration.between(from, to);
You can then query the hour/minute etc. with e.g. d.toMinutes().
By doing this
Time timeDiff = new Time(timeDiffLong);
you create a new time object, with timeDiffLong being the milliseconds since 1970-01-01 00:00 UTC. Since the difference is 30 minutes, the Time object will refer to 1970-01-01 00:30 UTC. But here comes the catch: timeDiff.toString() will output the time in the default time zone, that is, in most cases the time zone where you are currently are.
Long story short: Do not force an interval (duration, time difference) into a Time object. Either use a Duration class (Joda has one) or just do the division and modulo calculations yourself, as proposed by Kushan.
Looks like a duplicated question, have you seen already this answer?
How to find difference between two Joda-Time DateTimes in minutes
You should take a look at Joda time:
http://www.joda.org/joda-time/
Your problem is that when you create the time diff with
Time timeDiff = new Time(timeDiffLong);
and output that with System.out.println(timeDiff) then the result is shown for your local time zone. You can see that when you do this:
System.out.println(new Time(0));
TimeZone.setDefault(TimeZone.getTimeZone("PST"));
System.out.println(new Time(0));
That produces the following output here
00:00:00 //will probably be 20:00:00 for you
16:00:00
In short: Your time difference is shown as a GMT date converted to your local time zone and that is why its several hours off.

Android: Time stored in db is not the same as on phone

I'm using System.currentTimeMillis(); to get the current time for my 'modified' db field. I'm converting it to unix epoch by dividing it by 1000.
However, even when the phone's / emulator's date and time are set to true time, the value stored in the db is 2 hours earlier than true time.
I'm in GMT+2, but I can't find how this is affecting.
Doesn't System.currentTimeMillis(); get the current time for the current time settings ?
use Calendar.getInstance() instead, as this:
Calendar curTime = Calendar.getInstance();
This curTime object will be locale-specific.
From the API, in regards to currentTimeMillis()
This method shouldn't be used for measuring timeouts or other elapsed time measurements, as changing the system time can affect the results.
currentTimeMillis doesn't return timezone-dependent timestamps:
the difference, measured in milliseconds, between the current time and midnight, January 1, 1970 UTC.
However, it is good practice to store timestamps in UTC and to not include timezone offsets. To display the "correct" time, you can use a SimpleDateFormat:
SimpleDateFormat df = new SimpleDateFormat("HH:mm:ss");
// set your Timezone; or use TimeZone.getDefault() for the device timezone
df.setTimeZone(TimeZone.getTimeZone("Europe/Paris"));
String time = df.format(new Date(timestamp));
From the documentation:
"returns the difference, measured in milliseconds, between the current time and midnight, January 1, 1970 UTC"
It gives you the time, independant from your time zone. So you should calculate the correct time yourself.

How to get the time difference between 2 dates in millisec using JodaTime

I'm going to design an application, in which I need to get the exact time difference between two dates. Ex:
Date1:31/05/2011 12:54:00
Date2:31/05/2011 13:54:00
I tried using getTime() but I didn't get exact result.
The expected output for the above inputs is 3600000 (60 * 60 * 1000) millisec but I'm getting 46800000 (13 * 60 * 60 * 1000).
When I went through different java forums people are suggesting to use JodaTime.
Still I'm unable to get the exact result.
The timezone on I'm working is London(GMT).
Init two dateTime and use Period :
DateTime dt1 = new DateTime(2013,9,11,9,58,56);
DateTime dt2 = new DateTime(2013,9,11,9,58,59);
Period p = new Period(dt1, dt2, PeriodType.millis());
To get difference in milliseconds :
System.out.println(p.getValue(0));
public static long getDiff(Calender cal1, Calender cal2)
{
return Math.abs(cal1.getTimeInMillis() - cal2.getTimeInMillis());
}
Check out secondsBetween( )
Creates a Seconds representing the number of whole seconds between the
two specified partial datetimes.
The two partials must contain the same fields, for example you can
specify two LocalTime objects.
Parameters:
start - the start partial date, must not be null
end - the end partial date, must not be null
Returns:
the period in seconds
JodaTime is using machine time inside. So to find miliseconds, you can use a constant storing LocalDateTime referring to Jan 1, 1970(Because of UNIX Time).
Unix time, or POSIX time, is a system for describing points in time,
defined as the number of seconds elapsed since midnight proleptic
Coordinated Universal Time (UTC) of January 1, 1970, not counting leap
seconds. Then calculate the difference between your DateTime.
I tried like this;
public static void main(String[] args) {
final LocalDateTime JAN_1_1970 = new LocalDateTime(1970, 1, 1, 0, 0);
DateTime local = new DateTime().withZone(DateTimeZone.forID("Europe/Amsterdam"));
DateTime utc = new DateTime(DateTimeZone.UTC);
System.out.println("Europe/Amsterdam milis :" + new Duration(JAN_1_1970.toDateTime(DateTimeZone.forID("Europe/Amsterdam")), local).getMillis());
System.out.println("UTC milis :" + new Duration(JAN_1_1970.toDateTime(DateTimeZone.UTC), utc).getMillis());
}
And the result is;
Europe/Amsterdam milis :1429695646528
UTC milis :1429692046534
And #leonbloy write here a good comment.
Your local and utc represent the same instants of time, (only with
different timezones attached). Hence, getMillis() (which gives the
"physical" time interval elapsed from the "instant" corresponding to
the unix epoch), must return the same value.
Joda is a perfect library but if you need the difference between 2 dates in milliseconds you just should calculate difference between getTime(). If you get wrong results you have some problems with timezones or so. Typically it works.

Categories