Java
String Manipulation
Calendar Object
Date Conversion
Programming Tutorial

Convert a String to a Calendar object in Java

Codemia Knowledge Hub ·

To convert a date string to a Calendar in Java, parse it into a Date with SimpleDateFormat, then create a Calendar with Calendar.getInstance() and assign the date with setTime(). On Java 8 and later, the java.time API offers cleaner alternatives.

Calendar and SimpleDateFormat

Calendar, in the java.util package, is an abstract, flexible class with methods for converting between a specific instant and date and time fields such as YEAR, MONTH, DAY_OF_MONTH and HOUR. It can also compute a date and time from milliseconds.

SimpleDateFormat lets you define a pattern that matches the format of your string. A basic example:

java
1import java.text.ParseException;
2import java.text.SimpleDateFormat;
3import java.util.Calendar;
4import java.util.Date;
5
6public class StringToCalendarExample {
7    public static void main(String[] args) {
8        String dateString = "2023-10-14 15:30:00";
9        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
10
11        try {
12            Date date = format.parse(dateString);
13            Calendar calendar = Calendar.getInstance();
14            calendar.setTime(date);
15
16            System.out.println("Converted Calendar: " + calendar.getTime());
17        } catch (ParseException e) {
18            e.printStackTrace();
19        }
20    }
21}

How the conversion works

  1. Define the string and format: the string "2023-10-14 15:30:00" is paired with a SimpleDateFormat using the pattern "yyyy-MM-dd HH:mm:ss".
  2. Parse the string to a Date: parse() converts the string to a Date. It throws a ParseException if the string does not match the pattern, so it is wrapped in a try-catch block.
  3. Convert Date to Calendar: Calendar.getInstance() returns a Calendar, and setTime() assigns the Date to it.

Handling ParseException

ParseException is thrown when the date string does not match the specified format. Make sure the pattern lines up with the string format.

Thread safety, locale and time zone

  • Thread safety: SimpleDateFormat is not thread-safe. In multi-threaded code, use a separate instance per thread or synchronize access.
  • Locale and time zone: SimpleDateFormat can be initialized with a Locale and TimeZone, which matters for applications that handle dates across locales or time zones.

Date vs Calendar

AspectDate ClassCalendar Class
MutabilityMutableMutable
RepresentationRepresents a specific instant in timeRepresents a specific moment in time with fields like YEAR, MONTH, etc.
ManipulationLimited date manipulationRich set of utilities for date manipulation
DeprecationMany of its methods are deprecatedNot deprecated and encouraged for date manipulations

The java.time alternative

SimpleDateFormat and Calendar are enough for many tasks, but the Java 8 Date-Time API in the java.time package provides more modern, intuitive classes such as LocalDateTime and ZonedDateTime that solve many of the problems with Calendar and Date:

java
1import java.time.LocalDateTime;
2import java.time.format.DateTimeFormatter;
3
4public class ModernDateExample {
5    public static void main(String[] args) {
6        String dateString = "2023-10-14T15:30:00";
7        DateTimeFormatter formatter = DateTimeFormatter.ISO_LOCAL_DATE_TIME;
8        LocalDateTime dateTime = LocalDateTime.parse(dateString, formatter);
9
10        System.out.println("Converted LocalDateTime: " + dateTime);
11    }
12}

Both approaches have their uses. Choose based on your application's requirements and the Java version you target.


Course
Intermediate
27 lessons
14 hours
OOD Fundamentals

Master object-oriented design from first principles, SOLID, design patterns, and classic interview problems with hands-on coding.

View the course
Data Structures & Algorithms practice on Codemia

Step through 300+ coding interview problems with animated visualisers that show the data structure changing as the code runs. The Blind 75 are free.

Practice algorithms