Convert String to Date: The Java Ways
4 min readConverting strings to dates in programming is a common task that's more complex than it seems. This challenge is rooted in the wide range of date formats and the specifics of time zones. Developers face the task of parsing text into dates, dealing with formats like "MM/DD/YYYY" versus "DD/MM/YYYY," which can easily cause confusion and errors. The situation gets even trickier with leap years, daylight saving time changes, and localization needs. Handling these correctly is crucial for the accuracy of applications dealing with dates, making this task a significant technical challenge.
Converting a String to a Date in Java can be done in several ways, depending on the Java version you're using and whether you are incorporating external libraries. Below are the primary methods used in different versions of Java and through some commonly used external libraries.
Java DateTime
Java 8 introduced the java.time
package, providing a comprehensive model for date and time. It is the recommended approach for dealing with time in Java 8 and later.
For a simplest scenario parsing a date, we can use the LocalDate
.
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
public void computeTime() {
String dateStr = "2024-02-25";
LocalDate date = LocalDate.parse(dateStr, DateTimeFormatter.ISO_LOCAL_DATE);
}
Or LocalDateTime
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
public void computeTime() {
String dateTimeStr = "2024-02-25T15:30";
LocalDateTime dateTime = LocalDateTime.parse(dateTimeStr, DateTimeFormatter.ISO_LOCAL_DATE_TIME);
}
There are also variants such as timezone-based processing, duration calculation, instantaneous temporal, or date-amount of time in calendar system etc. For a complete list of APIs and implementations, please refer to the official documentation.
If your application has been using Java 8 and later, look no further! This is the right way to do it.
Using SimpleDateFormat (Before Java 8)
Before Java 8, SimpleDateFormat was commonly used for parsing and formatting dates. While SimpleDateFormat is a subclass of DateFormat, you can use DateFormat directly for parsing, albeit it's more common to use SimpleDateFormat for its flexibility in specifying patterns.
However, it's not thread-safe and less recommended if you're using Java 8 or later.
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
final static DateFormat formatter = new SimpleDateFormat(“MM/dd/yyyy");
public void computeTime() {
String dateStr = “02/25/2024";
try {
Date date = formatter.parse(dateStr);
System.out.println(date);
} catch (ParseException e) {
e.printStackTrace();
}
}
For beginners curious about what date formats signify, it might be helpful to break them down. For instance:
- y – Year (1996; 96)
- M – Month in year (July; Jul; 07)
- d – Day in month (1-31)
- E – Day name in week (Friday, Sunday)
- H – Hour in day (0-23)
- h – Hour in AM/PM (1-12)
- m – Minute in hour (0-60)
- s – Second in minute (0-60)
- a – AM/PM marker (AM, PM)
All format patterns have been defined in the java document
DateUtils in the Apache Library
Apache Commons Lang provides utilities for working with Java standard types, including date conversion utilities that simplify some tasks.
import org.apache.commons.lang3.time.DateUtils;
import java.text.ParseException;
import java.util.Date;
public void computeTime() {
String dateStr = "25-02-2024";
try {
Date date = DateUtils.parseDate(dateStr, "dd-MM-yyyy");
} catch (ParseException e) {
e.printStackTrace();
}
}
Using Calendar API (Pre-Java 8)
Before Java 8, Calendar was often used in conjunction with SimpleDateFormat to convert a string into a Date object, allowing for manipulation of different fields (like year, month, day).
import java.text.SimpleDateFormat;
import java.util.Calendar;
public void computeTime() {
try {
String dateStr = "25/02/2024";
SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
Calendar calendar = Calendar.getInstance();
calendar.setTime(sdf.parse(dateStr));
System.out.println(calendar.getTime());
} catch (Exception e) {
e.printStackTrace();
}
}
Using Apache Lang3's FastDateFormat
Apache Commons Lang3 offers FastDateFormat, which is a thread-safe alternative to SimpleDateFormat.
import org.apache.commons.lang3.time.FastDateFormat;
import java.util.Date;
public void computeTime() {
FastDateFormat fdf = FastDateFormat.getInstance("dd/MM/yyyy");
try {
Date date = fdf.parse("25/02/2024");
} catch (Exception e) {
e.printStackTrace();
}
}
Joda Time
Joda-Time was the de facto standard date and time library for Java prior to Java SE 8. Users are now asked to migrate to java.time (JSR-310). If you're working on legacy code or have specific reasons to use Joda-Time, it's still a viable choice.
Please exercise caution when implementing the Joda time, as it could potentially lead to security issues.
Google Gson
This is another option developers may consider, if using JSON. While not directly related to date parsing from a simple string, if your string is part of a JSON object, Google's Gson library can be used to automatically parse the date string into a Date object during the deserialization process.
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import java.util.Date;
class DateObject {
private Date date;
// Getters and setters
public Date getDate() {
return date;
}
public void setDate(Date date) {
this.date = date;
}
}
public class StringToDate {
public void computeTime() {
String json = "{\"date\":\"Feb 25, 2024\"}";
Gson gson = new GsonBuilder().setDateFormat("MMM dd, yyyy").create();
DateObject dateObject = gson.fromJson(json, DateObject.class);
//...
}
}
Summary
This article isn't exhaustive but aims to demonstrate the flexibility of the programming language through various approaches to a widely used technical procedure. It's our hope that, based on your application's specific needs and constraints, this will provide you with strategies to enhance your implementation.