How to calculate time difference considering day light saving? - java

I have function which calculated time difference between two dates in milliseconds. I am getting the time just before 1 hour of day light saving starts and then calculating time after 5 minutes of it. I is giving me 5 minutes of difference, One hour getting skipped. Do anyone having idea?

Just use this:
Suppose date1 is 20.03.2016, 13:00
date2 is 21.03.2016, 17:00
Calendar cal1 = Calendar.getInstance();
cal1.set(Hour_of_day,13);
cal1.set(Calendar.DAY_OF_MONTH, 20);
Calendar cal2 = Calendar.getInstance();
cal2.set(Hour_of_day,17);
cal2.set(Calendar.DAY_OF_MONTH, 21);
then difference of two gives time in milliseconds.
long time_in_milli = cal2.getTimeInMillis()-cal1.getTimeInMillis();
This would already take into account the day light saving thing.

I solved this by including timezone with date ex: Format your date with timezone like - "yyyy-MM-dd'T'HH:mm:ss.SSSZ" and then calculate time difference.

Related

Converting a Joda DateTime to another timezone without changing the time

I have tried all the ways in all the other questions on SO, and I can't get it to work. It is making me want to kill myself.
I have a set of times which are something like "04:00 AM AEST", except the AEST is a glitch, they should be GMT. What I want to do is change them to "04:00 GMT", and then convert them up to the correct AEST times (which in this example would be "14:00 AEST"). I have tried everything, and nothing works. The closest was to manually make a new DateTime using each individual value from the original date, e.g.
DateTime dt = new DateTime(origdate.year, origdate.month, origdate.day, origdate.hour, origdate.minute, origdate.second, timezone.GMT)
But for some reason the results came out four and a half minutes over, which is weird because timezones differ on hours and half hours.
1st Method By following lines you will get GMT time in specified format :
Calendar cal = Calendar.getInstance(TimeZone.getTimeZone("GMT"));
Date currentLocalTime = cal.getTime();
DateFormat date = new SimpleDateFormat("dd-MM-yyy HH:mm:ss z");
date.setTimeZone(TimeZone.getTimeZone("GMT"));
String gmtTime = date.format(currentLocalTime);
Hence, from GMT you can derive the time of any place.
2nd Method You can get system time of current place in milliseconds by:
Long current_time = System.currentTimeMillis() / 1000L;
Hope it helps.

Code to find day Difference

I am trying to write function to find day difference between two date it work ok but the result change some time in the same inputs .Let say the current date is 21/7/2014 the result some time is 567 and other time 566.
The code:
//TO GET THE CURRENT DATE
Calendar cal = Calendar.getInstance();
//THE CAL.ADD BECUSE THE 1ST MONTH IN THE YEAR IS 0 NOT 1
cal.add(Calendar.MONTH, 1);
//TO SET THE START DATE WICH IS 1/1/2013
Calendar startDate=Calendar.getInstance();
startDate.set(Calendar.DAY_OF_MONTH, 1);
startDate.set(Calendar.MONTH,1);
startDate.set(Calendar.YEAR, 2013);
//TO FIND THE DIFF BETWEEN THE START DATE AND CUREENT DATE , THE +1 BECUSE IT IS
ALWAYS LESS BY ONE DAY
long diff=(((cal.getTimeInMillis()-
startDate.getTimeInMillis())/(1000*60*60*24))+1);
I think this is because of the hours which get rounded in a strange way..
On my side when I add the following code it seems to work fine:
cal.set(Calendar.HOUR_OF_DAY, 1);
startDate.set(Calendar.HOUR_OF_DAY, 1);
The problem here is when you are instantiating a calendar, you are getting current date and time. So when you ignore time values it works perfectly.
Two compare two dates it's better to use Date class and java and use the following code
So your above code can be rewritten as
Date cal = new Date(114, 7, 21); //Date is 21/7/2014
Date startDate = new Date(113, 1, 1); Date is 1/1/2013
long newdiff = ((cal.getTime()-startDate.getTime())/(1000*60*60*24));
System.out.println(newdiff);
This time it will print 566 correctly (The actuall difference is 566)
The problem really is that suppose you are comparing today's date and tomorrow'date.
ie 21/7/2014 and 22/7/2014. The difference in days is one. If you run the program at 12:00 am midnight you will get 1. and at any other time after that it will result in 0. This is because of getting current time along with the date

Calendar getTimeInMills = July 4, 46452?

I am using Calendar on a Samsung Note. If I get a new instance of Calendar with Calendar.getInstance() and then call getTimeInMills() without doing anything else I get 1403732346277, which apparently is some value in the very far future.
I need to get a unix style timestamp. Is there some other preferred way to do this? Or some reason why the Calendar is returning this value (i.e. a standard adjustment I can make)?
Unix time represents the number of seconds from the epoch. As the name implies, getTimeInMillis() will return the number of milliseconds from the epoch. You need to divide your milliseconds by 1000 to get unix time.
long unixTime = Calendar.getInstance().getTimeInMillis() / 1000;
getTimeInMillis() returns you the time difference from Jan 1, 1970 with the calendar time in milliseconds.
Here is the calculation:
1403732346277 ms = 1403732346.277 seconds
1403732346.277 s = 389925.6517... hours
389925.6517 h = 16246.90 days
16246.90 days = 44.512 years (simple calculation: I divided by 365 just to get an approx idea. There are leap years in between.)
If you find the difference of current date from Jan 1, 1970, it is 44 years and ~6 months. So it seems to be giving you right time in milliseconds.
Or some reason why the Calendar is returning this value (i.e. a standard adjustment I can make)?
The java.util.Calendar API stores dates and times as the number of milliseconds that have elapsed from epoch (January 1, 1970 midnight UTC).
The number you got from Calendar.getInstance() - 1403732346277 - is what you'd expect. It's the number of milliseconds from epoch up to today at the exact time you called Calendar.getInstance().
If you want to extract more human-readable date/time information from that Calendar object, you can do something like:
Calendar cal = Calendar.getInstance();
int year = cal.get(Calendar.YEAR);
int month = cal.get(Calendar.MONTH);
int day = cal.get(Calendar.DAY_OF_MONTH);
int hour = cal.get(Calendar.HOUR_OF_DAY);
int minutes = cal.get(Calendar.MINUTE);
I need to get a unix style timestamp. Is there some other preferred way to do this?
As this post points out, you can get UNIX epoch by:
long unixTime = System.currentTimeMillis() / 1000L;

Want to switch on calendar date doing some calculation

I am getting the time in seconds from a function and I have to move further it into days and from the date 2/11/1970 00:00:00 till time in seconds I am getting will be covered. Please help me how to achieve this, or help me to do calculation on dates.
Not sure if I quite get your question, but if I do, have you tried the Calendar object?
Here's an example of how you could get the day out of the time in milliseconds:
Calendar cal = Calendar.getInstance();
Date date = new Date();
cal.setTimeInMillis(date.getTime());
int dayOfYear = cal.get(Calendar.DAY_OF_YEAR);
Take a look at the Joda date time API. IT should cater for your needs. This should point you in the right direction.

Finding the day in seconds since epoch, modulus not working

I have the following code to try and get the current day in seconds since epoch, by removing any seconds after 00:00:00 on any given day:
public void method(Date date) {
...
long dayDate = date.getTime() - (date.getTime() % 86400L);
...
}
For some reason, dayDate is simply being set to date.getTime(), and the mathematical operators are doing nothing here.
How would I go about fixing this?
I'll recommend that you use Joda Time library. It has most of the functions related to date, time and calendar that you'll ever need.
Like Ignacio already pointed out, date.getTime() returns the number of milliseconds since January 1st, 1970, so your line should have been:
long dayDate = date.getTime() - (date.getTime() % 86400000L);
Iif you are planning on creating a new Date with dayDate, make sure that it has the right timezone, e.g. it should be in the UTC/GMT timezone. Otherwise, strange things like this could happen:
Date epoch = new Date(0);
System.err.println(epoch);
which gives on my machine Thu Jan 01 01:00:00 CET 1970 because my dates are by default created in the CET (+1) timezone. So if you would use your code and you would create a new Date instance by using the long you calculated, you would end up with a date not at 0:00 on that day, but at 1:00.
However, without immediately resorting to Joda Time (which may not be an option in your project), you can use a Calendar to get the number of seconds:
// Create the calendar and set the date.
Calendar calendar = new GregorianCalendar();
calendar.setTime(date);
// Set the hours, minutes, etc. to 0.
calendar.set(Calendar.HOUR, 0);
calendar.set(Calendar.MINUTE, 0);
calendar.set(Calendar.SECOND, 0);
calendar.set(Calendar.MILLISECOND, 0);
calendar.set(Calendar.AM_PM, Calendar.AM);
long dayDate = calendar.getTime();

Categories

Resources