Question

How to Get the Current Unix Timestamp in Android Java

kotlinjavaandroidtimestampepoch

Question

I want to get the current timestamp in Android in a format like 1320917972.

For example, I tried this code:

int time = (int) System.currentTimeMillis();
Timestamp tsTemp = new Timestamp(time);
String ts = tsTemp.toString();

How can I correctly get the current timestamp in that numeric format?

Short Answer

By the end of this page, you will understand how to get the current Unix timestamp in Android Java, why System.currentTimeMillis() returns milliseconds, how to convert it to seconds, and how to avoid common mistakes such as using int instead of long.

Concept

A timestamp is a numeric representation of a point in time. In many programming tasks, when someone wants a value like 1320917972, they usually mean a Unix timestamp in seconds.

In Java and Android:

  • System.currentTimeMillis() returns the number of milliseconds since January 1, 1970 UTC.
  • A Unix timestamp like 1320917972 is usually measured in seconds, not milliseconds.

That means you typically need to divide the millisecond value by 1000.

long unixSeconds = System.currentTimeMillis() / 1000;

This matters because many APIs, databases, logs, analytics tools, and backend systems use Unix timestamps to store or exchange time values in a compact and standard format.

Your original code mixes several different ideas:

  • getting the current time
  • converting it to int
  • creating a Timestamp object
  • converting it to a formatted date string

If your goal is a number like 1320917972, you usually do not need Timestamp at all. You only need the current time and the correct unit.

Mental Model

Think of time like measuring distance.

  • System.currentTimeMillis() gives you the distance in millimeters.
  • A Unix timestamp like 1320917972 expects the distance in meters.

Both describe the same point, but in different units.

So if Java gives you milliseconds and you want Unix seconds, you simply shrink the unit:

  • milliseconds -> divide by 1000 -> seconds

Also think of data types like container sizes:

  • int is a smaller box
  • long is a larger box

Current time values are too large for an int, so you must use a long.

Take Quiz

Syntax and Examples

Basic syntax

long unixSeconds = System.currentTimeMillis() / 1000;

If you want it as a string:

String timestamp = String.valueOf(System.currentTimeMillis() / 1000);

Example: get current Unix timestamp in seconds

long timestamp = System.currentTimeMillis() / 1000;
System.out.println(timestamp);

Example output:

1715000000

Example: get current time in milliseconds

long timestampMillis = System.currentTimeMillis();
System.out.println(timestampMillis);

Example output:

1715000000123

Example: Android-friendly usage

long unixSeconds = System.currentTimeMillis() / 1000;
String unixSecondsText = Long.toString(unixSeconds);

This is useful when sending the value in a request, saving it in preferences, or logging it.

Modern Java alternative

If your Android API level and Java support allow it, you may also see:

long unixSeconds = java.time.Instant.now().getEpochSecond();

This directly returns Unix time in seconds.

Step by Step Execution

Consider this code:

long unixSeconds = System.currentTimeMillis() / 1000;
String result = Long.toString(unixSeconds);
System.out.println(result);

Step by step:

  1. System.currentTimeMillis() gets the current time in milliseconds since 1970.

    • Example value: 1715001234567
  2. / 1000 converts milliseconds to seconds.

    • Result: 1715001234
  3. The value is stored in a long.

    • This is important because time values are too large for int.
  4. Long.toString(unixSeconds) converts the number into text.

    • Result: "1715001234"
  5. System.out.println(result) prints the timestamp.

Why the original code is problematic

int time = (int) System.currentTimeMillis();
Timestamp tsTemp = new Timestamp(time);
String ts = tsTemp.toString();

What happens here:

  1. System.currentTimeMillis() returns a large long.
  2. Casting it to int cuts off data because int cannot hold such a large value.
  3. new Timestamp(time) creates a timestamp object from the wrong value.
  4. toString() produces a date-time string such as 2024-05-06 12:34:56.0, not a Unix numeric timestamp.

So the code is solving a different problem than the one you actually want to solve.

Real World Use Cases

Unix timestamps are commonly used in real applications because they are compact and easy to compare.

Common uses

  • API requests: sending created_at or expires_at
  • Token expiration: checking whether a login session is still valid
  • Caching: storing when data was last refreshed
  • Analytics: recording event times
  • Databases: saving timestamps as integers
  • Logs: writing machine-friendly event times

Android examples

  • Save the time when a user last opened the app
  • Store the time a notification was received
  • Compare whether cached data is older than 10 minutes
  • Send event timestamps to a backend service

Example:

long lastSync = System.currentTimeMillis() / 1000;

Later:

long now = System.currentTimeMillis() / 1000;
if (now - lastSync > 600) {
    // More than 10 minutes have passed
}
Take Quiz

Real Codebase Usage

In real projects, developers usually do more than just read the current time once. They use timestamps in patterns like validation, expiration checks, sorting, and persistence.

Common patterns

Guard clauses for expiration

long now = System.currentTimeMillis() / 1000;
if (tokenExpiry < now) {
    return;
}

Store timestamps in preferences

long savedAt = System.currentTimeMillis() / 1000;
sharedPreferences.edit().putLong("saved_at", savedAt).apply();

Compare age of cached data

long now = System.currentTimeMillis() / 1000;
long cacheAge = now - cachedAt;
if (cacheAge > 300) {
    // Refresh cache
}

Send numeric timestamps to APIs

Map<String, Object> payload = new HashMap<>();
payload.put("timestamp", System.currentTimeMillis() / 1000);

Good practice in codebases

  • Use long, not int
  • Decide clearly whether your app uses seconds or milliseconds
  • Keep units consistent across storage, API calls, and UI logic
  • Name variables clearly, such as createdAtSeconds or updatedAtMillis
  • Only format time as a readable string when displaying it to users

Common Mistakes

1. Using int instead of long

This is one of the biggest mistakes.

Broken code:

int time = (int) System.currentTimeMillis();

Why it is wrong:

  • System.currentTimeMillis() returns a long
  • Current time values are too large for int
  • Casting causes overflow and incorrect values

Correct code:

long time = System.currentTimeMillis();

2. Forgetting to convert milliseconds to seconds

Broken code:

long timestamp = System.currentTimeMillis();

If you expected 1320917972, this will not match because the result has extra digits.

Correct code:

long timestamp = System.currentTimeMillis() / 1000;

3. Using Timestamp.toString() when you want a numeric timestamp

Broken code:

Timestamp ts = new Timestamp(System.currentTimeMillis());
String value = ts.toString();

This returns a formatted date-time string, not a Unix number.

Correct code:

String value = Long.toString(System.currentTimeMillis() / 1000);

4. Mixing seconds and milliseconds

Broken code:

long start = System.currentTimeMillis() / 1000;
long end = System.currentTimeMillis();
long diff = end - start;

Why it is wrong:

  • start is in seconds
  • end is in milliseconds
  • You cannot subtract different units safely

Correct code:

long start = System.currentTimeMillis() / 1000;
long end = System.currentTimeMillis() / 1000;
long diff = end - start;

5. Formatting too early

If you turn the timestamp into a string too soon, it becomes harder to compare numerically.

Better approach:

  • Keep it as long for logic
  • Convert to String only when needed for output or transmission

Comparisons

ConceptWhat it returnsExample outputBest use
System.currentTimeMillis()Milliseconds since Unix epoch1715001234567Precise machine time
System.currentTimeMillis() / 1000Seconds since Unix epoch1715001234Unix timestamp for APIs and storage
new Timestamp(...).toString()Formatted date-time string2024-05-06 12:33:54.0Human-readable SQL-style time
Instant.now().getEpochSecond()Seconds since Unix epoch1715001234Modern Java time API

long vs int

TypeSizeSuitable for current timestamps?
int32-bitNo
long64-bitYes

Seconds vs milliseconds

UnitExampleWhen used
Seconds1715001234APIs, JWT expiry, compact storage
Milliseconds1715001234567Java system time, precise timing, Android internals
Take Quiz

Cheat Sheet

// Current time in milliseconds
long millis = System.currentTimeMillis();

// Current Unix timestamp in seconds
long seconds = System.currentTimeMillis() / 1000;

// As a String
String ts = Long.toString(System.currentTimeMillis() / 1000);

Rules

  • System.currentTimeMillis() returns milliseconds
  • Divide by 1000 to get seconds
  • Use long, not int
  • Use Timestamp.toString() only for readable date-time text, not Unix numeric format

Good variable names

  • createdAtMillis
  • createdAtSeconds
  • lastUpdatedAt
  • expiryTimeSeconds

Common edge cases

  • Do not mix seconds and milliseconds in calculations
  • Do not cast time to int
  • Do not assume all APIs use the same unit; always check documentation

FAQ

How do I get the current Unix timestamp in Android?

Use:

long timestamp = System.currentTimeMillis() / 1000;

This gives the current Unix timestamp in seconds.

Why is System.currentTimeMillis() too large?

Because it returns milliseconds, not seconds. Unix timestamps like 1320917972 are usually in seconds.

Should I use int or long for timestamps in Java?

Use long. Current timestamps are too large for int.

Why does Timestamp.toString() not give me 1320917972?

Because toString() formats the time as a date-time string, not as a Unix timestamp number.

What is the difference between epoch seconds and epoch milliseconds?

  • Epoch seconds: seconds since January 1, 1970 UTC
  • Epoch milliseconds: milliseconds since January 1, 1970 UTC

Milliseconds are more precise and have three extra digits.

Can I use Instant.now() on Android?

Yes, in supported environments and configurations. If you want maximum compatibility, System.currentTimeMillis() is the classic approach.

When should I keep the timestamp as a number instead of a string?

Keep it as a number when comparing, sorting, or calculating time differences. Convert it to a string only when displaying or sending it as text.

Take Quiz

Mini Project

Description

Build a small Android-style Java utility that stores the current Unix timestamp and checks whether cached data has expired. This demonstrates how timestamps are used in real apps for caching and freshness checks.

Goal

Create a simple program that saves the current Unix timestamp in seconds and determines whether data is older than 5 minutes.

Requirements

  • Get the current Unix timestamp in seconds
  • Store the timestamp in a variable named savedAt
  • Simulate a later time check using another timestamp
  • Print whether the cached data is still valid or expired
Take Quiz

Keep learning

Related questions

View more