What Can I used to replace this ?
Thanks for your help
What Can I used to replace this ?
Thanks for your help
Ideally, use Joda Time instead. It's an infinitely superior API to the built-in one. You'd then want to choose between LocalDateTime
and DateTime
depending on your exact requirements (it's a complicated area - I'm not going to try to summarise in a sentence or two, but the docs do a good job).
If absolutely necessary, use a java.util.Calendar and convert that to a Date
when you need to.
If you look at the Javadoc it points you towards using Calendar.
As of JDK version 1.1, replaced by
Calendar.set(year + 1900, month, date, hrs, min)
or GregorianCalendar(year + 1900, month, date, hrs, min).
If you look at the Date
constructor params you'll see why it was deprecated:
Parameters:
year - the year minus 1900. month - the month between 0-11. date - the day of the month between 1-31. hrs - the hours between 0-23. min - the minutes between 0-59.
year
isn't what you expect and neither is month
.
To represent the date you have mentioned you need to call Date
like this (not recommended)
new Date(2009-1900, 12-1, 9)
The alternative using Calendar
is
Calendar cal = Calendar.getInstance();
cal.set(2009, 11, 9); //year is as expected, month is zero based, date is as expected
Date dt = cal.getTime();
You can also use the SimpleDateFormat object:
import java.util.Date;
import java.text.SimpleDateFormat;
import java.text.ParseException;
public class DateTest {
public static void main( String [] args ) throws ParseException {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy, MM, dd");
Date date = sdf.parse("2009, 12, 9");
System.out.println( date );
}
}
Unfortunately date support in Java is completely awful. Officially, you'd probably have to do this with Calendar, but that shouldn't be necessary in my opinion. Like others have mentioned, Joda time is a lot better, but still not quite as easy to use as dates in Ruby on Rails.
I'm not aware of any Java package that gives you quite that amount of date support (Joda falls short a bit, but comes close), but in Groovy, using TimeCategory gives you very Ruby on Rails-like date support.
Calendar cal = Calendar.getInstance();
cal.set(2009, Calendar.DECEMBER, 12);
Notice that i didn't put 12 for december because it's actually 11 (january is 0).
Then, you can add or remove seconds, minutes, hours, days, months or year easily with :
cal.add(2, Calendar.HOUR);
cal.add(-5, Calendar.MONTH);
And finally, if you want a Date :
cal.getTime();
Tim, in your comments you mentioned that you are doing this in a GXT context - i.e. in GWT client code. GWT does not support GregorianCalendar and you will most likely not be able to put JodaTime through the GWTCompiler (you may be able to, but do you really want to).
I think you are left really with the option to using JNSI if you want to do calendar operations in GWT. See the Date class in JavaScript.