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

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.

Related

Converting date to milliseconds is giving inconsistent results in Android (java)

I'm trying to work with a calendar in android, and when I try to convert a date into milliseconds, I get different results on different runs.
When I print out the values of milliseconds1 and milliseconds2, I get different results different times!
My code is as follows:
Calendar calendar1 = Calendar.getInstance();
Calendar calendar2 = new GregorianCalendar(TimeZone.getTimeZone("GMT"));
calendar1.set(1997, 9, 3);
calendar2.set(1997, 9, 01);
long milliseconds1 = calendar1.getTimeInMillis();
long milliseconds2 = calendar2.getTimeInMillis();
Is this a bug in Java (or Android's implementation) or something like that?
The answer to your question is: No, this is not a bug in Java or Android. It is well documented behavior. A Calendar instance has more fields than YEAR, MONTH and DATE. You generate new calendar instances and only change those fields, leaving all other fields the way the were created. If you run your program twice in a row, the seconds and milliseconds will have changed in the mean time.
From JavaDoc:
Sets the values for the calendar fields YEAR, MONTH, and DAY_OF_MONTH.
Previous values of other calendar fields are retained. If this is not
desired, call clear() first.
In order to print the same value every time, you need to do this:
Calendar calendar1 = Calendar.getInstance();
Calendar calendar2 = new GregorianCalendar(TimeZone.getTimeZone("GMT"));
calendar1.clear();
calendar1.set(1997, 9, 3);
calendar2.clear();
calendar2.set(1997, 9, 1);
long milliseconds1 = calendar1.getTimeInMillis();
long milliseconds2 = calendar2.getTimeInMillis();

Android get difference in milliseconds between two dates

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.

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();
}

How to create a calendar object in Java

I need to turn a Date object into a calendar in Java, and try to access its field value for HOUR_OF_DAY. Does anybody know how to do it?
Use the setTime method:
Date date = new Date();
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
int hourOfDay = calendar.get(Calendar.HOUR_OF_DAY);
Calendar c = new GregorianCalendar();
c.setTime(date);
Something like this should work:
Calendar cal = Calendar.getInstance();
cal.setTime(date);
System.out.println(cal.get(Calendar.HOUR_OF_DAY));
Can I suggest using the Joda library if you're doing anything more than the most basic date/time work ?
DateTime dt = new DateTime();
int hour = dt.getHourOfDay();
I realise it's not quite what you're after, but the Joda date/time library offers the benefits of a much nicer and intuitive API, and avoids the non-intuitive gotchas of non-thread-safe date/time formatters It's well worth checking out.

Combining java.util.Dates to create a date-time

I have current have two UI components used to specify a date and a time. Both components return java.util.Date instances representing the calendar date and time respectively. My question is:
What is the best way to combine these values to create a java.util.Date instance representing the date and time? I would like to avoid dependencies on Joda or other 3rd party libraries.
My current solution looks like this (but is there a better way?):
Date date = ... // Calendar date
Date time = ... // Time
Calendar calendarA = Calendar.getInstance();
calendarA.setTime(date);
Calendar calendarB = Calendar.getInstance();
calendarB.setTime(time);
calendarA.set(Calendar.HOUR_OF_DAY, calendarB.get(Calendar.HOUR_OF_DAY));
calendarA.set(Calendar.MINUTE, calendarB.get(Calendar.MINUTE));
calendarA.set(Calendar.SECOND, calendarB.get(Calendar.SECOND));
calendarA.set(Calendar.MILLISECOND, calendarB.get(Calendar.MILLISECOND));
Date result = calendarA.getTime();
public Date dateTime(Date date, Date time) {
return new Date(
date.getYear(), date.getMonth(), date.getDay(),
time.getHours(), time.getMinutes(), time.getSeconds()
);
}
you can corvert this deprecated code to Calendar obtaining your solution.
Then my answer is: no, you cannot do better without using joda
NB
jodatime soon will be standardized with JSR 310
I think you're approach is the best you're likely to get without using Joda time. A solution using SimpleDateFormats might use fewer lines, but is not really giving you any benefit.
Using Calendar
public Date dateTime(Date date, Date time) {
Calendar aDate = Calendar.getInstance();
aDate.setTime(date);
Calendar aTime = Calendar.getInstance();
aTime.setTime(time);
Calendar aDateTime = Calendar.getInstance();
aDateTime.set(Calendar.DAY_OF_MONTH, aDate.get(Calendar.DAY_OF_MONTH));
aDateTime.set(Calendar.MONTH, aDate.get(Calendar.MONTH));
aDateTime.set(Calendar.YEAR, aDate.get(Calendar.YEAR));
aDateTime.set(Calendar.HOUR, aTime.get(Calendar.HOUR));
aDateTime.set(Calendar.MINUTE, aTime.get(Calendar.MINUTE));
aDateTime.set(Calendar.SECOND, aTime.get(Calendar.SECOND));
return aDateTime.getTime();
}

Categories