Java: Date from unix timestamp
A Unix timestamp in Java can be converted to a Date
object by using new Date(unixTimestamp * 1000L)
to convert seconds to milliseconds.
Learn to Time Travel: A Journey with java.util.Date
and java.time
Java provides two significant ways to play around with dates and times: the good old java.util.Date
class and the shiny new java.time
package that came swinging with Java 8.
A Date with java.util.Date
Believe me or not, this old warrior java.util.Date
is still kicking, especially when APIs demand its presence. It symbolizes a specific moment in time, millisecond accurate:
However, if the milliseconds value is already in your hands, why bother to convert?
When working with Date
, remember to pack time zones and formatting in your toolkit. Bring SimpleDateFormat
along to add a touch of elegance to your Date
object:
Living on the Edge with java.time
With the java.time
API, also known as JSR-310, Java has truly stepped into the future. If you're twiddling with Java 8 or newer, favor this API over java.util.Date
for superior capabilities and clarity:
For operations fully aware of time zones, ZonedDateTime
is your ultimate companion:
And, last but not least, you can swing Instant
directly to several types such as LocalDateTime
, making it an absolute charm for all applications:
Caveat Emptor: Mastering Tricky Scenarios and Compatibility
Wading through the oceans of timestamps and dates demands caution and foresight, particularly for special circumstances and cross compatibility.
When UNIX Meets String
There might be occasions when UNIX timestamps pose as string literals. Exercise caution and parse them to a numeric type before conversion:
Punk'd by Time Zones
Adept handling of time zones ensures accurate time across various regions, no nasty surprises:
Travelling from the Past to Present
A smooth ride between java.util.Date
and the java.time
types helps when interacting with legacy and modern code:
Pushing the Envelope with ThreeTen-Extra
For those who refuse to settle and demand more from date-time manipulations, the ThreeTen-Extra library complements java.time
by providing some extra kicks:
As you dive deeper down the rabbit hole of date-time manipulation, remember to make good use of the rich repertoire of various libraries tailored to your exact needs.
Was this article helpful?