Java How to Convert Date to String with Example
Date to a String by using SimpleDateFormat like this: new SimpleDateFormat("yyyy-MM-dd").format(date).Examples
How to Think About It
Algorithm
Code
import java.text.SimpleDateFormat; import java.util.Date; public class DateToStringExample { public static void main(String[] args) { Date date = new Date(124, 5, 1); // June 1, 2024 (year starts at 1900) SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd"); String dateString = formatter.format(date); System.out.println(dateString); } }
Dry Run
Let's trace converting June 1, 2024 to a string.
Create Date object
Date date = new Date(124, 5, 1); // represents 2024-06-01
Create formatter
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
Format date
String dateString = formatter.format(date); // "2024-06-01"
| Step | Action | Value |
|---|---|---|
| 1 | Date object | 2024-06-01 |
| 2 | Formatter pattern | yyyy-MM-dd |
| 3 | Formatted string | 2024-06-01 |
Why This Works
Step 1: Date object holds the date
The Date object stores the date internally as milliseconds since 1970.
Step 2: Formatter defines output style
The SimpleDateFormat object uses a pattern like yyyy-MM-dd to decide how the date looks as text.
Step 3: Format method converts date to string
Calling format(date) returns the date as a string in the chosen pattern.
Alternative Approaches
import java.time.LocalDate; import java.time.format.DateTimeFormatter; public class DateToStringJava8 { public static void main(String[] args) { LocalDate date = LocalDate.of(2024, 6, 1); DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd"); String dateString = date.format(formatter); System.out.println(dateString); } }
import java.util.Calendar; public class DateToStringCalendar { public static void main(String[] args) { Calendar cal = Calendar.getInstance(); cal.set(2024, Calendar.JUNE, 1); String dateString = String.format("%04d-%02d-%02d", cal.get(Calendar.YEAR), cal.get(Calendar.MONTH) + 1, cal.get(Calendar.DAY_OF_MONTH)); System.out.println(dateString); } }
Complexity: O(1) time, O(1) space
Time Complexity
Formatting a date is a fixed-time operation without loops, so it runs in constant time O(1).
Space Complexity
Only a small fixed amount of memory is used for the formatter and output string, so space is O(1).
Which Approach is Fastest?
Both SimpleDateFormat and DateTimeFormatter run in constant time; however, DateTimeFormatter is thread-safe and preferred in modern Java.
| Approach | Time | Space | Best For |
|---|---|---|---|
| SimpleDateFormat | O(1) | O(1) | Java versions before 8, simple formatting |
| DateTimeFormatter | O(1) | O(1) | Java 8+, thread-safe, modern code |
| String.format with Calendar | O(1) | O(1) | Manual control, but verbose and error-prone |
SimpleDateFormat or DateTimeFormatter with a clear pattern to get consistent date strings.Date constructor, causing off-by-one month errors.