Main Tutorials

Java – Convert Date to Calendar example

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


	Calendar calendar = Calendar.getInstance();
	Date newDate = calendar.setTime(date);

A Full example

DateAndCalendar.java

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

public class DateAndCalendar {
	public static void main(String[] argv) throws ParseException {

		//1. Create a Date from String
		SimpleDateFormat sdf = new SimpleDateFormat("dd-M-yyyy hh:mm:ss");
		String dateInString = "22-01-2015 10:20:56";
		Date date = sdf.parse(dateInString);
                DateAndCalendar obj = new DateAndCalendar();

		//2. Test - Convert Date to Calendar
		Calendar calendar = obj.dateToCalendar(date);
		System.out.println(calendar.getTime());
		
		//3. Test - Convert Calendar to Date
		Date newDate = obj.calendarToDate(calendar);
		System.out.println(newDate);

	}

	//Convert Date to Calendar
	private Calendar dateToCalendar(Date date) {

		Calendar calendar = Calendar.getInstance();
		calendar.setTime(date);
		return calendar;

	}

	//Convert Calendar to Date
	private Date calendarToDate(Calendar calendar) {
		return calendar.getTime();
	}

}

Output


Thu Jan 22 10:20:56 SGT 2015
Thu Jan 22 10:20:56 SGT 2015

About Author

author image
Founder of Mkyong.com, love Java and open source stuff. Follow him on Twitter. If you like my tutorials, consider make a donation to these charities.

Comments

Subscribe
Notify of
5 Comments
Most Voted
Newest Oldest
Inline Feedbacks
View all comments
Rigo
5 years ago

This is not completely reliable, as setTime does not set all the fields.
In this example if you converted a Date to a Calendar, then ran calendar.get(Calendar.DAY_OF_WEEK) it would return the present weekday, instead of the given date’s.

IdontWantToCodeAnymore();
5 years ago
Reply to  Rigo

You rite it just happened to me rn… how should I convert it?

IdontWantToCodeAnymore();
5 years ago

SimpleDateFormat sdf = new SimpleDateFormat(“dd-M-yyyy hh:mm:ss”);
String dateInString = “22-01-2015 10:20:56”;
You are giving a single-digit format for the month and passing ’01’, is that right? or do you need to put exactly the same amount

Dino
6 years ago

What is DateAndCalendar obj = new DateAndCalendar(); coming from??

Deba
3 years ago
Reply to  Dino

See the code properly.. you will get it. Happy Debugging,