Development & Utilities

How Do I Calculate Time Differences Using Unix Timestamps?

Learn to calculate time differences using Unix timestamps, handle time zones, and work with milliseconds and microseconds.

By Inventive HQ Team

Understanding Unix Timestamps for Time Calculations

To calculate the time difference between two Unix timestamps, subtract the earlier one from the later one — the result is the elapsed time in seconds. From there, divide by 60 for minutes, 3600 for hours, or 86400 for days. This works because a Unix timestamp (also called epoch or POSIX time) is a single number: the count of seconds since January 1, 1970, 00:00:00 UTC. There is no calendar math, no time-zone offset, and no daylight-saving adjustment to worry about — just subtraction of two absolute numbers.

That's the summary an AI overview gives you. What it can't give you is the part that actually breaks in production: the two timestamps must be in the same unit (both seconds or both milliseconds), the difference is unaffected by time zones and DST because the values are absolute UTC, and the only true elapsed-time answer comes from the raw subtraction — not from subtracting local wall-clock times. This page gives you the reference tables, the per-language code, and a diagram of exactly why the arithmetic is safe.

Want to subtract two dates without writing code? Try our free Unix Timestamp Converter to convert each timestamp and verify the difference instantly. If you are working with calendar dates rather than epoch numbers, our Time Duration Calculator finds the time between two dates — including the hours, minutes, and total days between them — without any code at all.

Try it in your browser below — everything runs client-side:

Loading interactive tool...
Subtracting two Unix timestamps on the UTC timeline A number line showing a start timestamp 1704067200 and an end timestamp 1704153600. The gap between them equals 86400 seconds, which is exactly one day. end − start = elapsed seconds One absolute UTC timeline — no time zone, no DST start 1704067200 Jan 1, 2024 00:00 UTC end 1704153600 Jan 2, 2024 00:00 UTC 86,400 s = 1 day

Basic Time Difference Calculation

Simple Example:

Start time: 1704067200 (Jan 1, 2024 00:00:00 UTC)
End time:   1704153600 (Jan 2, 2024 00:00:00 UTC)
Difference: 1704153600 - 1704067200 = 86400 seconds = 1 day

The difference is always in seconds with Unix timestamps. Convert to other units as needed:

Seconds: diff = end_timestamp - start_timestamp
Minutes: diff / 60
Hours:   diff / 3600
Days:    diff / 86400

Time Unit Conversion Reference

Divide the seconds difference by the constant below to get any other unit. Keep this table handy — these six constants cover almost every timestamp calculation you will ever do.

UnitSeconds per unitConvert seconds → unitExact?
Second1diffExact
Minute60diff / 60Exact
Hour3,600diff / 3600Exact
Day86,400diff / 86400Exact
Week604,800diff / 604800Exact
Month (~30 d)2,592,000diff / 2592000Approximate
Year (~365 d)31,536,000diff / 31536000Approximate

Seconds through weeks are exact because those units always contain the same number of seconds. Months and years vary in length (28–31 days; 365 or 366 days), so treat them as estimates and reach for a date library when precision matters.

Subtract Two Timestamps in Any Language

The logic is identical everywhere — end - start — but the unit each platform hands you differs. This table is the "which line do I write" cheat sheet:

Language / systemGet "now" as a timestampNative unitDifference in seconds
JavaScriptDate.now()milliseconds(end - start) / 1000
JavaScript (already seconds)Math.floor(Date.now()/1000)secondsend - start
Pythontime.time()seconds (float)end - start
PHPtime()seconds$end - $start
SQL (MySQL)UNIX_TIMESTAMP()secondsend - start
JavaSystem.currentTimeMillis()milliseconds(end - start) / 1000
Gotime.Now().Unix()secondsend - start

The single row to memorize: JavaScript and Java give you milliseconds, so divide by 1000 to get seconds. Everything else is already in seconds.

Practical Examples in Different Languages

JavaScript:

const startTime = 1704067200; // Jan 1, 2024
const endTime = 1704153600;   // Jan 2, 2024

const secondsDiff = endTime - startTime; // 86400
const minutesDiff = secondsDiff / 60;    // 1440
const hoursDiff = secondsDiff / 3600;    // 24
const daysDiff = secondsDiff / 86400;    // 1

console.log(`Difference: ${daysDiff} days`);

Python:

start_time = 1704067200  # Jan 1, 2024
end_time = 1704153600    # Jan 2, 2024

seconds_diff = end_time - start_time  # 86400
minutes_diff = seconds_diff / 60      # 1440
hours_diff = seconds_diff / 3600      # 24
days_diff = seconds_diff / 86400      # 1.0

print(f"Difference: {days_diff} days")

PHP:

$startTime = 1704067200; // Jan 1, 2024
$endTime = 1704153600;   // Jan 2, 2024

$secondsDiff = $endTime - $startTime; // 86400
$minutesDiff = $secondsDiff / 60;     // 1440
$hoursDiff = $secondsDiff / 3600;     // 24
$daysDiff = $secondsDiff / 86400;     // 1

echo "Difference: $daysDiff days";

SQL:

SELECT
  (end_timestamp - start_timestamp) AS seconds_diff,
  (end_timestamp - start_timestamp) / 60 AS minutes_diff,
  (end_timestamp - start_timestamp) / 3600 AS hours_diff,
  (end_timestamp - start_timestamp) / 86400 AS days_diff
FROM events
WHERE event_id = 123;

Handling Time Zones

Unix timestamps are always in UTC (Coordinated Universal Time). They're timezone-agnostic—the same Unix timestamp represents the same moment worldwide.

Example:

Timestamp: 1704067200
UTC Time: 2024-01-01 00:00:00 UTC
EST (UTC-5): 2023-12-31 19:00:00
JST (UTC+9): 2024-01-01 09:00:00
Sydney (UTC+11): 2024-01-01 11:00:00

The timestamp is identical; only the local time representation differs.

Why this makes subtraction DST-safe: Because both timestamps live on the absolute UTC timeline, a daylight-saving transition happening between your two events does not distort the result. Subtracting the raw timestamps returns the true number of elapsed seconds — no "spring forward" hour lost, no "fall back" hour double-counted. The classic off-by-one-hour bug only appears when you subtract local wall-clock times instead of timestamps. Store and compare as Unix timestamps and the problem disappears.

Converting to Local Time:

JavaScript:

const timestamp = 1704067200;
const date = new Date(timestamp * 1000); // JavaScript uses milliseconds

const utcTime = date.toUTCString();
const localTime = date.toLocaleString();
const estTime = date.toLocaleString('en-US', { timeZone: 'America/New_York' });

console.log(`UTC: ${utcTime}`);
console.log(`Local: ${localTime}`);
console.log(`EST: ${estTime}`);
Advertisement

Calculating Duration

From Start Time to Now:

JavaScript:

const startTime = Math.floor(Date.now() / 1000); // Current Unix timestamp
const now = Math.floor(Date.now() / 1000);
const elapsedSeconds = now - startTime;

console.log(`Elapsed: ${elapsedSeconds} seconds`);

Python:

import time

start_time = time.time()  # Current Unix timestamp
# ... do something ...
now = time.time()
elapsed_seconds = now - start_time

print(f"Elapsed: {elapsed_seconds:.2f} seconds")

Milliseconds and Microseconds

Some systems use milliseconds (JavaScript, Node.js) or microseconds instead of seconds.

Converting Units:

Unix seconds: 1704067200
Unix milliseconds: 1704067200000 (seconds × 1,000)
Unix microseconds: 1704067200000000 (seconds × 1,000,000)

JavaScript (Uses Milliseconds):

// Current timestamp in milliseconds
const now = Date.now(); // e.g., 1704153600000

// Convert to seconds
const seconds = Math.floor(now / 1000); // 1704153600

// Convert seconds back to milliseconds
const ms = seconds * 1000;

Python (Uses Seconds):

import time

# Current timestamp in seconds
now = time.time()  # e.g., 1704153600.123

# Current timestamp in milliseconds
now_ms = int(time.time() * 1000)  # 1704153600123

Formatted Duration Output

Converting a difference into human-readable format:

JavaScript:

function formatDuration(seconds) {
  const units = [
    { name: 'year', seconds: 31536000 },
    { name: 'month', seconds: 2592000 },
    { name: 'day', seconds: 86400 },
    { name: 'hour', seconds: 3600 },
    { name: 'minute', seconds: 60 },
    { name: 'second', seconds: 1 }
  ];

  const parts = [];
  let remaining = Math.floor(seconds);

  for (const unit of units) {
    const count = Math.floor(remaining / unit.seconds);
    if (count > 0) {
      parts.push(`${count} ${unit.name}${count > 1 ? 's' : ''}`);
      remaining -= count * unit.seconds;
    }
  }

  return parts.join(', ');
}

console.log(formatDuration(90061)); // "1 day, 1 hour, 1 minute, 1 second"

Python:

def format_duration(seconds):
    units = [
        ('year', 31536000),
        ('month', 2592000),
        ('day', 86400),
        ('hour', 3600),
        ('minute', 60),
        ('second', 1)
    ]

    parts = []
    remaining = int(seconds)

    for unit_name, unit_seconds in units:
        count = remaining // unit_seconds
        if count > 0:
            plural = 's' if count > 1 else ''
            parts.append(f"{count} {unit_name}{plural}")
            remaining -= count * unit_seconds

    return ', '.join(parts)

print(format_duration(90061))  # "1 day, 1 hour, 1 minute, 1 second"

Age Calculation

Calculating Someone's Age:

function calculateAge(birthTimestamp) {
  const now = Math.floor(Date.now() / 1000);
  const ageSeconds = now - birthTimestamp;
  const ageYears = ageSeconds / 31536000;
  return Math.floor(ageYears);
}

const birthDate = new Date('1990-01-15').getTime() / 1000;
console.log(`Age: ${calculateAge(birthDate)}`);

Expired vs Valid Timestamps

Checking if Something is Expired:

JavaScript:

const expirationTime = 1706745600; // Expiration timestamp
const now = Math.floor(Date.now() / 1000);

if (now > expirationTime) {
  console.log("Expired");
} else {
  const secondsUntilExpiry = expirationTime - now;
  const daysUntilExpiry = secondsUntilExpiry / 86400;
  console.log(`Expires in ${daysUntilExpiry.toFixed(1)} days`);
}

Working with Intervals

Scheduling at Regular Intervals:

JavaScript:

const startTime = Math.floor(Date.now() / 1000);
const intervalSeconds = 3600; // Every hour

setInterval(() => {
  const now = Math.floor(Date.now() / 1000);
  const elapsedIntervals = Math.floor((now - startTime) / intervalSeconds);
  console.log(`Interval ${elapsedIntervals} occurred`);
}, intervalSeconds * 1000);

Database Queries for Time Differences

SQL Examples:

-- Events happened within the last 24 hours
SELECT * FROM events
WHERE timestamp > UNIX_TIMESTAMP() - 86400;

-- Events that lasted more than 1 hour
SELECT id, end_timestamp - start_timestamp AS duration_seconds
FROM events
WHERE (end_timestamp - start_timestamp) > 3600;

-- Group by duration ranges
SELECT
  CASE
    WHEN duration < 60 THEN 'less than 1 minute'
    WHEN duration < 3600 THEN 'less than 1 hour'
    WHEN duration < 86400 THEN 'less than 1 day'
    ELSE 'more than 1 day'
  END AS duration_range,
  COUNT(*) AS count
FROM (
  SELECT (end_timestamp - start_timestamp) AS duration
  FROM events
) subquery
GROUP BY duration_range;

Common Mistakes

Forgetting JavaScript Uses Milliseconds:

// Wrong
const timestamp = 1704067200;
const date = new Date(timestamp); // Interprets as milliseconds!
// Gives date in 1970 (55 years ago)

// Correct
const date = new Date(timestamp * 1000);

Not Accounting for Leap Seconds: Unix timestamps assume no leap seconds exist (they're skipped), which can cause issues in precise systems.

Month/Year Approximations:

Months are NOT consistent length
A "month" varies: 28-31 days
Use date libraries for precise month/year math

Using Unix Timestamp Converter Tool

The Unix Timestamp Converter helps:

  1. Convert human-readable dates to timestamps
  2. Convert timestamps to human-readable format
  3. Calculate differences between dates
  4. Verify timestamp values

Use it to validate your calculations before implementing in code.

Conclusion: Simple Subtraction for Time Differences

Calculating time differences with Unix timestamps is simple: subtract one from the other. The result is in seconds; convert as needed. The beauty of Unix timestamps is their timezone-independence and simplicity—they work identically across all programming languages and systems. Understanding timestamp arithmetic is fundamental for any developer working with dates, scheduling, logging, or time-based operations.

Frequently Asked Questions

How do I calculate the difference between two Unix timestamps?

Subtract the earlier timestamp from the later one. Because a Unix timestamp is just a count of seconds since 1 January 1970 00:00:00 UTC, the difference is a plain integer number of seconds. Divide that result by 60 for minutes, 3600 for hours, or 86400 for days. For example, 1704153600 minus 1704067200 equals 86400 seconds, which is exactly one day. The only rule that matters is that both timestamps must be in the same unit — two seconds values or two millisecond values, never one of each.

Why do I need to multiply by 1000 in JavaScript?

JavaScript's Date object works in milliseconds, but most Unix timestamps and most APIs are in seconds. If you pass a seconds value straight into new Date(1704067200) it is read as 1.7 million milliseconds after the epoch — a date in January 1970, roughly 55 years wrong. Multiply the seconds value by 1000 first: new Date(1704067200 * 1000). When you subtract two timestamps you do not need the multiply, because the seconds difference is already correct; you only convert to milliseconds when handing a value to Date.

Do time zones affect the difference between two Unix timestamps?

No. A Unix timestamp is an absolute point on the UTC timeline, so it carries no time zone. The same instant has the same timestamp whether it is recorded in New York, London, or Sydney. That means subtracting two timestamps always gives the true elapsed physical time, regardless of where either event happened. Time zones only matter when you convert a timestamp into a human-readable local date for display — not when you do the arithmetic.

Is subtracting Unix timestamps safe across daylight saving time changes?

Yes. Daylight saving time shifts the local clock, not the underlying UTC timeline that Unix timestamps count. Because both timestamps are absolute UTC-based seconds, subtracting them gives the real number of seconds that elapsed even if a DST transition happened in between. This is exactly why storing and comparing times as Unix timestamps avoids the classic "off by one hour" bugs you get when you subtract local wall-clock times.

How many seconds are in a day, hour, and minute?

There are 60 seconds in a minute, 3600 seconds in an hour, and 86400 seconds in a day (24 x 3600). A week is 604800 seconds. Months and years are not fixed lengths, so 2592000 (30 days) and 31536000 (365 days) are approximations only — use a real date library for accurate month or year math.

How do I convert a timestamp difference into days, hours, minutes, and seconds?

Work down from the largest unit using integer division and remainders. Days equal the difference divided by 86400; take the remainder, divide by 3600 for hours; take that remainder, divide by 60 for minutes; the final remainder is seconds. For 90061 seconds this gives 1 day, 1 hour, 1 minute, and 1 second. This "greatest unit first" approach is how a human-readable duration formatter works in any language.

What is the most common bug when calculating timestamp differences?

Mixing units — subtracting a milliseconds timestamp from a seconds timestamp, or vice versa. The result is off by a factor of 1000 and usually looks absurd (millions of years, or a fraction of a second). A quick sanity check is digit count: a current seconds timestamp has 10 digits, milliseconds has 13, and microseconds has 16. Normalise both values to the same unit before subtracting.

How do I check whether a Unix timestamp has expired?

Compare it against the current time. Get "now" as a Unix timestamp (Math.floor(Date.now() / 1000) in JavaScript, or int(time.time()) in Python) and check whether it is greater than the expiration timestamp. If now is larger, the deadline has passed. To show time remaining, subtract now from the expiration timestamp and convert the resulting seconds to days or hours. This is exactly how JWT and session-token expiry checks work.

unix-timestamptimedate-mathprogrammingutilities