Android get difference in milliseconds between two dates - java

I have Integer fields:
currentYear,currentMonth,currentDay,currentHour,currentMinute and nextYear,nextMonth,nextDay,nextHour,nextMinute.
How I can get difference between those two spots in time in milliseconds.
I found a way using Date() object, but those functions seems to be depricated, so it's little risky.
Any other way?

Use GregorianCalendar to create the date, and take the diff as you otherwise would.
GregorianCalendar currentDay=new GregorianCalendar (currentYear,currentMonth,currentDay,currentHour,currentMinute,0);
GregorianCalendar nextDay=new GregorianCalendar (nextYear,nextMonth,nextDay,nextHour,nextMinute,0);
diff_in_ms=nextDay. getTimeInMillis()-currentDay. getTimeInMillis();

Create a Calendar object for currenDay and nextDay, turn them into longs, then subtract. For example:
Calendar currentDate = Calendar.getInstance();
Calendar.set(Calendar.MONTH, currentMonth - 1); // January is 0, Feb is 1, etc.
Calendar.set(Calendar.DATE, currentDay);
// set the year, hour, minute, second, and millisecond
long currentDateInMillis = currentDate.getTimeInMillis();
Calendar nextDate = Calendar.getInstance();
// set the month, date, year, hour, minute, second, and millisecond
long nextDateInMillis = nextDate.getTimeInMillis();
return nextDateInMillis - currentDateInMillis; // this is what you want
If you don't like the confusion around the Calendar class, you can check out the Joda time library.

Related

How to set some days on Calendar.DAY_OF_WEEK

I need to set some days in method set. I try to use:
c.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY);
c.set(Calendar.DAY_OF_WEEK, Calendar.WEDNESDAY);
but with this way set only Wednesday.
Thank you and sorry for my english :)
The Calendar does not function as you expect it to. From the JavaDoc:
The Calendar class is an abstract class that provides methods for
converting between a specific instant in time and a set of calendar
fields such as YEAR, MONTH, DAY_OF_MONTH, HOUR, and so on, and for
manipulating the calendar fields, such as getting the date of the next
week. An instant in time can be represented by a millisecond value
that is an offset from the Epoch, January 1, 1970 00:00:00.000 GMT
(Gregorian).
Notice that the documentation states a specific instant in time. This implies the Calendar can only be based off of one point in time from epoch.
When you use the set method you are adjusting the specific instant in time through each call. So first it gets set to Monday then Wednesday.
You could use a List<Calendar> to store multiple Calendar instances set to your desired days.
public class CalendarTest {
public static void main(String[] args) {
Calendar cal1 = Calendar.getInstance();
Calendar cal2 = Calendar.getInstance();
cal1.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY);
cal2.set(Calendar.DAY_OF_WEEK, Calendar.WEDNESDAY);
List<Calendar> calendars = Arrays.asList(cal1, cal2);
}
}
public static String getDay(String day,String month,String year){
int mm = Integer.parseInt(month);
int dd = Integer.parseInt(day);
int yy = Integer.parseInt(year);
LocalDate dt = LocalDate.of(yy, mm, dd);
return dt.getDayOfWeek().toString().toUpperCase();
}

Date picking and finding difference

I am a novice to Java programming using Netbeans. I have added jCalendar to my GUI to pick a date.
I have entered this line in Events -> "property change" code of jCalendar button,
Date date=jcalendar1.getDate();
So that I get the date immediately when it is changed. Am I right?
The purpose:
I want to find the difference in milliseconds from the afternoon (12:00 pm) of this date above to NOW (current date and time).
There are several programs showing the date difference but all have dates hardcoded and being a newbie i do not know how to replace it with the date that is picked. (also i am confused between the objects Date and Calendar, not able to understand the difference between them). For example, a piece from here:
http://www.java2s.com/Code/Java/Data-type/ReturnsaDatesetjusttoNoontotheclosestpossiblemillisecondoftheday.htm
if (day == null) day = new Date();
cal.setTime(day);
cal.set(Calendar.HOUR_OF_DAY, 12);
cal.set(Calendar.MINUTE, cal.getMinimum(Calendar.MINUTE));
cal.set(Calendar.SECOND, cal.getMinimum(Calendar.SECOND));
cal.set(Calendar.MILLISECOND, cal.getMinimum(Calendar.MILLISECOND));
return cal.getTime();
Here day is a Date object. How is cal (a calendar object) linked to it to enter the time. How should the cal object be defined first? How can I use this or anything else in your opinion for my program. A piece of code with detail comments will be more helpful
thanks!
Instead of using :
Date day = new Date();
Use:
Calendar cal = Calendar.getInstance();
cal.set (...);
Date date = new Date(cal.getTimeInMillis());
Worth abstracting this stuff out to a DateUtils class or similar, with something like the following:
public static Date create(int year, int month, int day, int hour, int minute, int second) {
return new Date(getTimeInMillis(year, month, day, hour, minute, second));
}
public static long getTimeInMillis(int year, int month, int day, int hour, int minute, int second, int milliseconds) {
Calendar cal = Calendar.getInstance();
cal.clear();
cal.set(year, month, day, hour, minute, second);
cal.set(Calendar.MILLISECOND, milliseconds);
return cal.getTimeInMillis();
}

Problems with the Date 31-12-9999 in java

My program needs to represent this date as a java.sql.date object , but it seems that when I create a new date (using the calendar) and set it to '9999-12-31' and finally convert this java.util.date object to a java.sql.date object, this date is converted to something like '000-01-31'.
Calendar calendar = Calendar.getInstance();
calendar.set(9999, 12, 31);
infinityDate = new java.sql.Date(normalizeDate(calendar.getTime()).getTime());
infinityDate should be 31-12-9999
but when my code reaches here :
if(otherDate.equals(infinityDate))
{// Do stuff}
It never goes into the if condition as the infinityDate has for some reason been changed to 31-01-000, even though otherDate is infact '31-12-9999'.
The fact that otherDate is 31-12-9999 tells me that java can represent this dates , but for some reason , when I construct it using a calendar it changes the date. (otherDate comes from a jdbc statement which fetches data from a database)
This reference date '31-12-9999' has been fixed by some client , so it cannot be changed and my program has to be able to compare some incoming date values with this.
Does anyone know why this is happening , I realize that http://en.wikipedia.org/wiki/Year_10,000_problem may be a problem for dates after year 9999 , but I should be safe by a day.
EDIT : The Normalize date method only "normalizes the given date to midnight of that day"
private static java.util.Date normalizeDate(java.util.Date date) {
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
calendar.set(Calendar.HOUR_OF_DAY, 0);
calendar.set(Calendar.MINUTE, 0);
calendar.set(Calendar.SECOND, 0);
calendar.set(Calendar.MILLISECOND, 0);
date = calendar.getTime();
return date;
}
But , this issue was appearing before I was normalizing the date , I normalized it in an attempt to fix this.
Months are zero indexed. Use 11 for December, not 12. This is why you are rolling over the year.
Calendar.MONTH is zero-based. The call
calendar.set(9999, 12, 31);
sets the date to "the 31st day in the 13th month of the year 9999", which is then implicitly converted to the 1st month of the year 10000. It would result in an exception if you first called
calendar.setLenient(false);
Check hours, minutes, seconds and milliseconds that are held into these 2 date objects. I believe they are different.
If your want to compare the date (year, month, day) only you should probably create your custom Comparator and use it.

Calendar returning the wrong time

The time displayed is way ahead of what I expected. I'm parsing a date string and turning it into milliseconds.
year = Integer.parseInt(m1.group(1));
mo = Integer.parseInt(m1.group(2));
day = Integer.parseInt(m1.group(3));
hr = Integer.parseInt(m1.group(4));
min = Integer.parseInt(m1.group(5));
sec = Integer.parseInt(m1.group(6));
and here I set the Calendar
Calendar cal = Calendar.getInstance();
cal.set(year, mo, day, hr, min, sec);
time = cal.getTimeInMillis();
If you check out the calendar documentation here, then visit here, you'll see that January is month 0. You'll want to change your code to mo = Integer.parseInt(m1.group(2))-1;
You should probably use DateFormatter to parse the date string (rather than rolling your own).
Other than that, make sure that you have the proper time zone and understand that month number one is February (not January).

Creating a Java date from YMD HMS values without using deprecated code

I'm spending some time with Java again after a long break on the .NET side. I came across this code:
Date date = new Date(Date.UTC(y - 1900, m - 1, d, h, M, s));
Unfortunately Date.UTC has been deprecated for a while. So, what is an equivalent replacement that won't cause compiler warnings?
Try this
GregorianCalendar cal = new GregorianCalendar();
cal.set(year, month, day,
hour, minute, second);
Date date = cal.getTime();
You GregorianCalendar also supports setting the TimeZone if needed.
Use Calendar
Specifically use set() method, Also there is very good API joda time
Update
Calendar cal = Calendar.getInstance(TimeZone.getTimeZone("UTC"));
cal.set(y, m, d, h, M, s);
Date date = cal.getTime();
Use Joda-time. It's just awesome and a huge leap from the standard Java Date/Time libraries:
new DateTime(year, monthOfYear, dayOfMonth, hourOfDay,
minuteOfHour, secondOfMinute, millisOfSecond,
DateTimeZone.UTC);
But if you don't like having all those params which are easily confused you can also use take builder-style approach:
new DateTime()
.withYear(2011)
.withMonthOfYear(6)
.withDayOfMonth(12)
// etc...
.withZone(DateTimeZone.UTC);
Each call to withXxxx() returns a copy so DateTime remains immutable.

Categories