Java: Date to Calendar Conversion

The java.util.Calendar 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 month. 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).

Calendar’s getInstance method returns a Calendar object whose calendar fields have been initialized with the current date and time:

Calendar calendar= Calendar.getInstance();

In below example you will see conversion from Java Date object to Calendar and Calendar to Java Date.

Example

package com.date;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

public class DateString2CalendarConversion {
private static final String MAIN_DATE="2012-02-16T18:30:00.000Z";
private static final String MAIN_DATE_FORMAT="yyyy-MM-dd'T'hh:mm:ss.SSS'Z'";
private static final String DATE_FORMAT1="yyyyMMdd";
public static void main(String[] args) {
SimpleDateFormat formatter=new SimpleDateFormat(MAIN_DATE_FORMAT);
try
{
Date date =formatter.parse(MAIN_DATE);
//convert date date to calendar
Calendar calendar=Calendar.getInstance();
calendar.setTime(date);
System.out.println(calendar);

//convert Calendar to date
Date newDate=calendar.getTime();
formatter=new SimpleDateFormat(DATE_FORMAT1);
System.out.println(formatter.format(newDate));

}
catch(ParseException ex)
{
 ex.printStackTrace();
}<span 				data-mce-type="bookmark" 				id="mce_SELREST_start" 				data-mce-style="overflow:hidden;line-height:0" 				style="overflow:hidden;line-height:0" 			></span>
}
}

Output


java.util.GregorianCalendar[time=1329445800000,areFieldsSet=true,areAllFieldsSet=true,lenient=true,zone=sun.util.calendar.ZoneInfo[id="America/Los_Angeles",offset=-28800000,dstSavings=3600000,useDaylight=true,transitions=185,lastRule=java.util.SimpleTimeZone[id=America/Los_Angeles,offset=-28800000,dstSavings=3600000,useDaylight=true,startYear=0,startMode=3,startMonth=2,startDay=8,startDayOfWeek=1,startTime=7200000,startTimeMode=0,endMode=3,endMonth=10,endDay=1,endDayOfWeek=1,endTime=7200000,endTimeMode=0]],firstDayOfWeek=1,minimalDaysInFirstWeek=1,ERA=1,YEAR=2012,MONTH=1,WEEK_OF_YEAR=7,WEEK_OF_MONTH=3,DAY_OF_MONTH=16,DAY_OF_YEAR=47,DAY_OF_WEEK=5,DAY_OF_WEEK_IN_MONTH=3,AM_PM=1,HOUR=6,HOUR_OF_DAY=18,MINUTE=30,SECOND=0,MILLISECOND=0,ZONE_OFFSET=-28800000,DST_OFFSET=0]
20120216

Advertisements

This site uses Akismet to reduce spam. Learn how your comment data is processed.