Explain Codes LogoExplain Codes Logo

How to convert current date into string in Java?

java
date-formatting
datetime-api
thread-safety
Alex KataevbyAlex Kataev·Feb 16, 2025
TLDR

If you need to super-speedily convert the current date to a string in Java using SimpleDateFormat:

SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd"); String today = sdf.format(new Date()); System.out.println(today); // BOOM! You've got today's date!

Instantiate SimpleDateFormat and then simply call format on a fresh Date instance.

Now, let's upgrade to Java 8+ approach with DateTimeFormatter and LocalDate:

DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd"); String today = LocalDate.now().format(formatter); System.out.println(today); // This ain't your grandpa's Java!

The deep dive // Essential things to mind

The timezone conundrum

Dates and times can be trickier than a box of confounded springs! Enter the dreaded timezones and localization. Neglect these, and you face a date that tells the wrong time:

ZoneId zoneId = ZoneId.of("America/New_York"); LocalDate today = LocalDate.now(zoneId); // New York, New York, so nice they named it twice!

Dressing up your date

Different date formats are as numerous as stars in the sky. Adjust SimpleDateFormat and DateTimeFormatter patterns to fit the occasion:

DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"); String dateTimeString = LocalDateTime.now().format(formatter); // It's party time with time!

Thread safety in the wild

Always keep DateTimeFormatter close! Being immutable and thread-safe, it's your best friend in a multi-threaded jungle - leaving SimpleDateFormat in the cold.

Beyond the basics // Advanced stuff

Date-time ballet with databases

Modern applications often throw a direct line to databases for date-time objects. Java 8's date-time API dances with your database gracefully:

// Example of using LocalDateTime with JDBC LocalDateTime now = LocalDateTime.now(); preparedStatement.setObject(1, now); // Wham, bam, thank you ma'am!

Extra Java-time fun

For date-time enthusiasts, libraries such as ThreeTen-Extra add a new dimension of fun. These are perfect for the most convoluted of date-time arithmetic or non-standard calendar systems.

Just a quickie

For a no-nonsense, quick and dirty string representation of the current date and time, use new Date().toString():

String simpleDateString = new Date().toString(); System.out.println(simpleDateString); // Quicker than Netflix binging!