How to convert current date into string in Java?
If you need to super-speedily convert the current date to a string in Java using SimpleDateFormat
:
Instantiate SimpleDateFormat
and then simply call format
on a fresh Date
instance.
Now, let's upgrade to Java 8+ approach with DateTimeFormatter
and LocalDate
:
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:
Dressing up your date
Different date formats are as numerous as stars in the sky. Adjust SimpleDateFormat
and DateTimeFormatter
patterns to fit the occasion:
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:
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()
:
Was this article helpful?