Explain Codes LogoExplain Codes Logo

Android Get Current timestamp?

java
timestamp
unix-time
date-formatting
Anton ShumikhinbyAnton ShumikhinΒ·Nov 27, 2024
⚑TLDR

To obtain the current timestamp, we use System.currentTimeMillis(), specifying milliseconds since Unix epoch.

long timestampMillis = System.currentTimeMillis(); // πŸ¦– Fossil evidence of this exact moment long timestampSeconds = timestampMillis / 1000; // Seconds since Unix epoch, return of the dinosaur

To render the timestamp in a human-friendly date format, we utilize SimpleDateFormat:

SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.getDefault()); String formattedDate = sdf.format(new Date(timestampMillis)); // Dressing up the timestamp for the party

For precision requirements in time-sensitive applications, consider using SystemClock.elapsedRealtime() to ensure robustness and avoid wall clock time issues.

Get timestamp in seconds using Unix time

Access the Unix time, defined as number of seconds that have elapsed since 1970-01-01 00:00:00 UTC, excluding leap seconds.

Quick conversion to Unix time

long unixTimeSeconds = TimeUnit.MILLISECONDS.toSeconds(System.currentTimeMillis()); // Because who has got the time for milliseconds? String unixTimeString = Long.toString(unixTimeSeconds); // Making it readable; we aren’t machines!

Dealing with time zones

When working with SimpleDateFormat, it's crucial to account for time zones. Use TimeZone to align timestamps accurately.

Exception handling

While formatting and parsing dates, don't overlook exceptions. Enclose time operations in a try-catch block for stability.

Advanced usage

Tips, tricks, and things to watch out; the timestamp saga continues.

Handling system time changes

Subscribe for Intent broadcasts related to system time changes, and respond suitably to maintain application consistency.

Moving beyond SimpleDateFormat

For thread-safe alternatives, meet java.time.format.DateTimeFormatter from Java 8 Time API - backported to Android.

Using SystemClock.elapsedRealtime()

For measuring intervals or elapsed time, SystemClock.elapsedRealtime() provides a monotonic clock unaffected by wall clock time discrepancies.