I'm using the PrettyTime java library for a variety of date/time processing in my java app, such as converting MySQL format dates/datetime strings into java dates, or the vice versa.
However, I see that date.getYear(), date.getMonth()
, etc, are all deprecated, and it says to use Calendar instead. But PrettyTime only returns its results as Date objects, and I see no way to convert the Date objects into calendar objects.
In the documentation for Calendar, the only mention I see of Date
is the method setTime(Date date), but the method name is ambigious, and the documentation is not clear on what calling this method would actually do. Obviously I can't just do calendar.set( date.getYear(), date.getMonth(), ..)
etc, as those methods of Date
are deprecated.
So how can I convert a given Date object to Calendar?
In Java, you can use calendar. setTime(date) to convert a Date object to a Calendar object.
DateFormat formatter = new SimpleDateFormat("yyyyMMdd"); date = (Date)formatter. parse(date. toString()); DateFormat is used to convert Strings to Dates ( parse() ) or Dates to Strings ( format() ).
You can use following code to convert string date to calender format. String stringDate="23-Aug-10"; SimpleDateFormat formatter = new SimpleDateFormat("dd-MM-yyyy"); Date date = formatter. parse(stringDate); Calendar calender = Calendar. getInstance(); calender.
Calendar cal = Calendar.getInstance();
cal.setTime(date);
You can get the calendar in different locales as well if you want.
You could also do
cal.setTimeInMillis(date.getTime());
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With