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
1320917972is 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
Timestampobject - 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
1320917972expects 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:
intis a smaller boxlongis a larger box
Current time values are too large for an int, so you must use a long.
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
System.currentTimeMillis() / ;
Long.toString(unixSeconds);
Step by Step Execution
Consider this code:
long unixSeconds = System.currentTimeMillis() / 1000;
String result = Long.toString(unixSeconds);
System.out.println(result);
Step by step:
-
System.currentTimeMillis()gets the current time in milliseconds since 1970.- Example value:
1715001234567
- Example value:
-
/ 1000converts milliseconds to seconds.- Result:
1715001234
- Result:
-
The value is stored in a
long.- This is important because time values are too large for
int.
- This is important because time values are too large for
-
Long.toString(unixSeconds)converts the number into text.- Result:
"1715001234"
- Result:
-
System.out.println(result)prints the timestamp.
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_atorexpires_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
}
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(, System.currentTimeMillis() / );
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 along- 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:
Comparisons
| Concept | What it returns | Example output | Best use |
|---|---|---|---|
System.currentTimeMillis() | Milliseconds since Unix epoch | 1715001234567 | Precise machine time |
System.currentTimeMillis() / 1000 | Seconds since Unix epoch | 1715001234 | Unix timestamp for APIs and storage |
new Timestamp(...).toString() | Formatted date-time string | 2024-05-06 12:33:54.0 | Human-readable SQL-style time |
Instant.now().getEpochSecond() | Seconds since Unix epoch | 1715001234 |
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
1000to get seconds - Use
long, notint - Use
Timestamp.toString()only for readable date-time text, not Unix numeric format
Good variable names
createdAtMilliscreatedAtSecondslastUpdatedAtexpiryTimeSeconds
Common edge cases
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.
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
Keep learning
Related questions
Accessing Kotlin Extension Functions from Java
Learn how Kotlin extension functions are compiled and how to call them correctly from Java with clear examples and common pitfalls.
Android AlarmManager Example: Scheduling Tasks with AlarmManager
Learn how to use Android AlarmManager to schedule tasks, set alarms, and handle broadcasts with a simple beginner example.
Android Foreground Service Notification Channels in Kotlin
Learn why startForeground fails on Android 8.1 and how to create a valid notification channel for foreground services in Kotlin.