How to get current timestamp in string format in Java? "yyyy.MM.dd.HH.mm.ss"
To quickly obtain the current timestamp in "yyyy.MM.dd.HH.mm.ss"
format using SimpleDateFormat
:
This concise line of code generates a formatted date string, which perfectly embodies time's relentless march.
Taming time with java.time
"Java 8" showed us the future by introducing the futuristic java.time
package. Here's how you wield time as a weapon with java.time
:
Venture into newer territories with java.time
, as it provides a compelling toolset for working with dates and times.
Time zones: Your secret weapon
Time zones are an essential, yet elusive part of working with date-times. Specify a time zone like a pro:
This ensures that the temporal rift in the space-time continuum—I mean, your timestamp—reflects your local time.
The hidden dangers of SimpleDateFormat
Beware, SimpleDateFormat
lures us with its simplicity, but is not thread-safe! In a multi-threaded Jedi battle—ahem—environment, prefer the immutable, thread-safe DateTimeFormatter
. Avoid synchronization issues like the plague!
Graduating to java.time
Even old school Date
and SimpleDateFormat
are bowing to modern java.time
API. This transition not just rejuvenates your application, but also paves the way for robustness and readability. Embrace java.time
gradually, and you'll find date-time operations becoming more intuitive.
Mind the pitfalls
Watch out, time-traveller! Here be dragons:
- Thread Safety: Unlike
DateTimeFormatter
,SimpleDateFormat
isn't thread-safe. - API Misuse: Don't create
new Date()
without parameters if you are representing now. - Format String Mishaps: Ensure your format string in
SimpleDateFormat
orDateTimeFormatter
is exactly your desired output. - Database Interactions: Mind the gap! For JDBC interactions, be wise and use JDBC 4.2 or above for seamless
java.time
support.
Unleashing java.time
Master java.time
like a boss with these also-practical tips:
- Substitute
Instant
forDate
when storing timestamps. ZonedDateTime
is your friend when you need both date-time and time-zone information.- Embrace
java.time
’s immutable objects to keep unexpected side-effects at bay.
Was this article helpful?