Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert java.util.Date objects into Calendar objects? [duplicate]

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?

like image 757
Ali Avatar asked Oct 12 '13 02:10

Ali


People also ask

How do you convert a Date object to a calendar object?

In Java, you can use calendar. setTime(date) to convert a Date object to a Calendar object.

How do I convert a date to a calendar date?

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() ).

How do I convert a string to a calendar instance?

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.


1 Answers

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());
like image 129
Jeff Storey Avatar answered Sep 22 '22 07:09

Jeff Storey