Converting a date String and time String to a Calendar object and vice versa

In a scenario where the date is selected using a date selector dropdown, and time through a time textfield the date and time strings from the UI may need to be converted to a Calendar object.

Here is sample code how this can be done:

//converts date and time Strings to calendar object from UI inputs

public Calendar setDateAndTime(String strDate, String strTime) {
		Calendar calendar = Calendar.getInstance();
		Calendar calendar2 = Calendar.getInstance();
		try {
			DateFormat dateFormat = new SimpleDateFormat("MM/dd/yyyy");
			Date date = dateFormat.parse(strDate);
			if (strTime != null) {
				dateFormat = new SimpleDateFormat("kk:mm");
				date = dateFormat.parse(strTime);
				calendar.set(Calendar.MINUTE, calendar2.get(Calendar.MINUTE));
		} catch (ParseException e) {
			// todo - handle exception....
		return calendar;

//converts Calendar object to String date to display on UI

public String formatTime(Calendar calendar) {
		String strTime = null;
		SimpleDateFormat simpleDateFormat = new SimpleDateFormat("kk:mm");
		strTime = simpleDateFormat.format(calendar.getTime());
		return strTime;

//converts Calendar object to String time to display on UI

	public String formatDate(Calendar calendar) {
		String strDate = null;
		SimpleDateFormat simpleDateFormat = new SimpleDateFormat("MM/dd/yyyy");
		strDate = simpleDateFormat.format(calendar.getTime());
		return strDate;

About cuppajavamattiz
Matty Jacob - Avid technical blogger with interests in J2EE, Web Application Servers, Web frameworks, Open source libraries, Relational Databases, Web Services, Source control repositories, ETL, IDE Tools and related technologies.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: