timestamper.online

Complete Guide to Unix Timestamps

By Unix Timestamp Converter • Last updated 2025-10-22

Master everything about Unix timestamps from basic concepts to advanced applications

Beginner FriendlyReal ExamplesCode SamplesBest Practices
Table of Contents

Core Concepts

  • • What is a Unix timestamp
  • • History and evolution
  • • Different precision levels
  • • Timestamps vs other time formats

Practical Applications

  • • Usage in programming languages
  • • Database time field design
  • • API development best practices
  • • Common issues and solutions
What is a Unix Timestamp?

A Unix timestamp is a time representation method that indicates the number of seconds that have elapsed since January 1, 1970, 00:00:00 UTC (Coordinated Universal Time). This starting point is called the "Unix Epoch."

Why January 1, 1970?

The choice of January 1, 1970, was not arbitrary. This date was a reasonable starting point during Unix system development - not too early to cause negative number issues, and not too late to affect historical data representation. This standard is now widely adopted as the universal time representation standard in computer systems.

Timestamp Examples

Current timestamp:1761134669
Unix Epoch:0
Y2K:946684800

Timestamp Features

  • • Universal global standard
  • • Timezone independent
  • • Easy calculation and comparison
  • • Compact storage
  • • Adjustable precision
Timestamp Precision Explained

Unix timestamps can have different precision levels. Understanding them is crucial for choosing the correct format and avoiding bugs.

Seconds (s)10 digits

The most common format, used by most backend systems and databases.

Example
1640995200
Milliseconds (ms)13 digits

Standard in JavaScript (`Date.now()`). A frequent source of bugs when mixing with second-based systems.

Example
1640995200000
Nanoseconds (ns)19 digits

Used in high-precision systems. Exceeds JavaScript's `Number.MAX_SAFE_INTEGER`, requiring `BigInt`.

Example
1640995200000000000

Common Pitfall

The most frequent bug in time manipulation is mistaking seconds for milliseconds. Passing a 10-digit timestamp to a function expecting 13 digits (like `new Date()` in JS) will result in a date in early 1970.

Timestamp Handling in Programming Languages

Different programming languages handle Unix timestamps in slightly different ways. Here are timestamp operation examples for mainstream programming languages:

JavaScriptFrontend and Node.js Development

The most important thing to remember when working with JavaScript is that its native `Date` object operates with milliseconds since the epoch, not seconds. This is a common source of bugs when interacting with backend systems (like Python, PHP, or SQL databases) that often use second-precision timestamps.

1. Get the Current Unix Timestamp

Use `Date.now()` to get the current timestamp in milliseconds. To get it in seconds, you must divide by 1000 and remove the decimal part.

javascript
// Get current timestamp in MILLISECONDS
const timestampInMs = Date.now();
console.log(timestampInMs); // Example: 1678886400123

// Get current timestamp in SECONDS
const timestampInSeconds = Math.floor(Date.now() / 1000);
console.log(timestampInSeconds); // Example: 1678886400

2. Convert a Unix Timestamp to a Date Object

To convert a timestamp into a `Date` object, pass the timestamp to the `new Date()` constructor. Remember to use milliseconds!

javascript
const timestampInMs = 1678886400123;

// Create a Date object
const dateObject = new Date(timestampInMs);
console.log(dateObject.toISOString()); // "2023-03-15T13:20:00.123Z"
Handling Timestamps in Seconds

If you receive a timestamp in seconds from a backend API, you must convert it to milliseconds before passing it to the `Date` constructor.

javascript
const timestampInSeconds = 1678886400;

// Multiply by 1000 to convert to milliseconds
const dateObject = new Date(timestampInSeconds * 1000);

console.log(dateObject.toISOString()); // "2023-03-15T13:20:00.000Z"

3. Convert a Date Object to a Unix Timestamp

To get the millisecond timestamp from a `Date` object, use the `.getTime()` method.

javascript
const myDate = new Date('2024-10-12T10:30:00Z');

// Get the timestamp in milliseconds
const timestampInMs = myDate.getTime();
console.log(timestampInMs); // 1728712200000

// To get the timestamp in seconds for a backend
const timestampInSeconds = Math.floor(myDate.getTime() / 1000);
console.log(timestampInSeconds); // 1728712200

PythonData Processing and Backend Development

Python provides powerful, built-in modules to handle Unix timestamps: `time` and `datetime`. A Unix timestamp is a floating-point number in Python, which allows for sub-second precision.

1. Convert Unix Timestamp to a Readable Date

The `datetime.fromtimestamp()` method is perfect for this.

python
import datetime

# The Unix timestamp (seconds since epoch)
timestamp = 1678886400

# Convert to a datetime object
date_object = datetime.datetime.fromtimestamp(timestamp)

# Format it into a readable string
readable_date = date_object.strftime("%Y-%m-%d %H:%M:%S")
print(f"Readable Date: {readable_date}")

2. Convert a Date to a Unix Timestamp

To perform the reverse, create a `datetime` object and call the `.timestamp()` method.

python
import datetime

my_date = datetime.datetime(2024, 10, 12, 10, 30, 0)

unix_timestamp = my_date.timestamp()
print(f"Unix Timestamp: {unix_timestamp}")

3. Handling Timezones

By default, `datetime.fromtimestamp()` uses your system's local timezone. To handle timezones correctly, work with UTC.

python
import datetime

timestamp = 1678886400

# Convert to a timezone-aware datetime object in UTC
utc_date = datetime.datetime.fromtimestamp(timestamp, tz=datetime.timezone.utc)

print(f"UTC Date: {utc_date.strftime('%Y-%m-%d %H:%M:%S %Z')}")

PHPWeb Backend Development

PHP traditionally works with Unix timestamps in seconds. You can use procedural functions or the modern, recommended object-oriented approach.

1. Procedural Functions (`time`, `date`, `strtotime`)

php
<?php
// Get current timestamp
$currentTimestamp = time();

// Timestamp to readable date
$readableDate = date('Y-m-d H:i:s', $currentTimestamp);

// Readable date to timestamp
$timestamp = strtotime('2024-10-12 10:30:00');
?>

2. Object-Oriented Way (`DateTimeImmutable`)

This approach is more robust and readable. `DateTimeImmutable` is preferred as it prevents accidental modification.

php
<?php
$timestamp = 1678886400;

// Create a DateTimeImmutable object from a timestamp (use '@')
$date = new DateTimeImmutable('@' . $timestamp);

echo $date->format('Y-m-d H:i:s');
?>

3. Handling Timezones

`DateTime` objects make timezone handling explicit and easy.

php
<?php
$timestamp = 1678886400; // This is always UTC

$utcDate = new DateTimeImmutable('@' . $timestamp, new DateTimeZone('UTC'));

// Convert to another timezone
$nyDate = $utcDate->setTimezone(new DateTimeZone('America/New_York'));
echo 'New York Time: ' . $nyDate->format('Y-m-d H:i:s');
?>

JavaEnterprise Application Development

Since Java 8, the `java.time` package (JSR-310) provides immutable, thread-safe classes. The core class for a timestamp is `Instant`.

1. Get the Current Unix Timestamp

`Instant.now()` returns the current moment in UTC. You can get seconds or milliseconds from it.

java
import java.time.Instant;

Instant now = Instant.now();
long epochSeconds = now.getEpochSecond();
long epochMillis = now.toEpochMilli();

2. Convert a Unix Timestamp to a Date Object

Create an `Instant` from a timestamp using `ofEpochSecond` or `ofEpochMilli`.

java
import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneOffset;

long timestampInSeconds = 1678886400L;
Instant instant = Instant.ofEpochSecond(timestampInSeconds);

// To view it, convert to LocalDateTime in a specific timezone
LocalDateTime dateTime = LocalDateTime.ofInstant(instant, ZoneOffset.UTC);

3. Convert a Date Object to a Unix Timestamp

To go the other way, create a `LocalDateTime` and convert it to an `Instant`, specifying a timezone.

java
import java.time.LocalDateTime;
import java.time.ZoneOffset;

LocalDateTime localDateTime = LocalDateTime.of(2024, 10, 12, 10, 30, 0);

// Convert to a timestamp, assuming UTC
long timestamp = localDateTime.toEpochSecond(ZoneOffset.UTC);
Common Issues and Solutions

Year 2038 Problem (Y2K38)

In 32-bit systems, the maximum value for signed integers is 2,147,483,647, corresponding to January 19, 2038, 03:14:07 UTC. Exceeding this time will cause overflow.

Solutions:

  • • Use 64-bit systems and 64-bit integers
  • • Modern programming languages support 64-bit timestamps by default
  • • Use BIGINT type in databases to store timestamps
  • • Update legacy systems promptly

Timezone Handling Issues

Unix timestamps are inherently UTC time, but timezone conversion needs to be considered during display and input.

Best Practices:

  • • Use UTC time uniformly on the server side
  • • Display according to user timezone on the client side
  • • Store timestamps rather than local time in databases
  • • Clearly indicate timezone information in API interfaces

Precision Selection Issues

Different application scenarios require different time precision levels. Choosing appropriate precision can optimize performance and storage.

Selection Guide:

  • • Logging: Second precision is usually sufficient
  • • Frontend applications: Millisecond precision is convenient for processing
  • • High-frequency trading: Microsecond or nanosecond precision
  • • Data analysis: Choose based on analysis granularity
Development Best Practices

Database Design

  • Use BIGINT to store timestamps, supporting millisecond precision
  • Create indexes for time fields to optimize query performance
  • Add created_at and updated_at fields
  • Consider adding deleted_at field for soft deletion

API Design

  • Consistently use ISO 8601 format for returning time
  • Provide both timestamp and formatted time
  • Clearly indicate timezone information
  • Support time range query parameters

Frontend Handling

  • Display time using user's local timezone
  • Provide relative time display (e.g., "2 hours ago")
  • Cache timezone conversion results
  • Handle daylight saving time changes

Security Considerations

  • Validate timestamp ranges to prevent anomalous values
  • Prevent timestamp injection attacks
  • Log operation timestamps
  • Use server time as authoritative time
Related Tools and Resources

Online Conversion Tool

Use our online tool to quickly convert timestamp formats

Start Converting

API Documentation

Integrate our API into your applications

View API

Unix Timestamp to Datetime

Convert Unix epoch (seconds) to human-readable datetime in ISO 8601, RFC 3339, UTC and local formats.

Open Converter
Timezones and Daylight Saving Time (DST)

The Golden Rule: Store UTC, Display Local

Unix timestamps are always in UTC. To avoid countless bugs, your systems should adhere to a simple rule: always store timestamps as UTC. Only convert to a user's local timezone for display purposes at the very last moment (e.g., in the UI). Never store local time strings like "2023-03-15 09:20:00" in your database.

The timezone issue comes when you display or parse human-readable dates. Daylight Saving Time (DST) can shift local time by an hour, which frequently causes off-by-one-hour bugs in calendar features, reporting, and booking systems.

Display in User Timezone (JavaScript)

JavaScript
const ts = 1704067200000; // 2024-01-01T00:00:00.000Z (ms)
// Use Intl API to format in user's locale/timezone
const fmt = new Intl.DateTimeFormat(undefined, {
  timeZone: Intl.DateTimeFormat().resolvedOptions().timeZone,
  year: 'numeric', month: '2-digit', day: '2-digit',
  hour: '2-digit', minute: '2-digit', second: '2-digit'
});
console.log(fmt.format(new Date(ts)));

Working with UTC and Local (Python)

Python
from datetime import datetime, timezone

ts = 1704067200  # seconds
# UTC
utc_dt = datetime.fromtimestamp(ts, tz=timezone.utc)
print('UTC:', utc_dt.isoformat())
# Local
local_dt = datetime.fromtimestamp(ts)
print('Local:', local_dt.isoformat())

DST Pitfall

Never hardcode timezone offsets (like `+0800`). Use proper timezone databases (IANA tz, e.g., "America/New_York"). Offsets change with DST and political decisions.

Formatting and Parsing Correctly

Prefer ISO 8601 for interchange. When parsing in JavaScript, new Date('YYYY-MM-DD') may be treated as UTC in some engines and local in others—always include timezone or use Date.UTC.

JavaScript

JavaScript
// Avoid ambiguous parsing
const d1 = new Date('2024-01-01T00:00:00Z'); // explicit UTC
const d2 = new Date(Date.UTC(2024, 0, 1, 0, 0, 0)); // UTC via parts

// Format ISO
console.log(d1.toISOString()); // 2024-01-01T00:00:00.000Z

SQL (PostgreSQL)

SQL
-- Store as BIGINT (ms) or TIMESTAMP WITH TIME ZONE
-- Convert BIGINT ms to timestamptz
SELECT to_timestamp(1704067200000 / 1000.0) AT TIME ZONE 'UTC';

-- Output ISO 8601
SELECT to_char(now() AT TIME ZONE 'UTC', 'YYYY-MM-DD"T"HH24:MI:SS.MS"Z"');
More Language Examples (Go, C#, Ruby, SQL)

Go

Go
package main
import (
  	"fmt"
  	"time"
)
func main() {
  now := time.Now()
  fmt.Println(now.Unix())      // seconds
  fmt.Println(now.UnixMilli()) // milliseconds
  // Parse ISO
  t, _ := time.Parse(time.RFC3339, "2024-01-01T00:00:00Z")
  fmt.Println(t.Unix())
}

C#

C#
using System;
class P {
  static void Main() {
    var now = DateTimeOffset.UtcNow;
    Console.WriteLine(now.ToUnixTimeSeconds());
    Console.WriteLine(now.ToUnixTimeMilliseconds());
    var dt = DateTime.Parse("2024-01-01T00:00:00Z", null, System.Globalization.DateTimeStyles.AdjustToUniversal);
    Console.WriteLine(new DateTimeOffset(dt).ToUnixTimeSeconds());
  }
}

Ruby

Ruby
t = Time.now
puts t.to_i        # seconds
puts (t.to_f * 1000).to_i  # milliseconds
# Parse ISO
require 'time'
iso = Time.parse('2024-01-01T00:00:00Z')
puts iso.to_i

MySQL

SQL
-- Convert milliseconds BIGINT to DATETIME
SELECT FROM_UNIXTIME(1704067200000 / 1000);
-- Current timestamp (ms)
SELECT UNIX_TIMESTAMP(CURRENT_TIMESTAMP(3)) * 1000;
Frequently Asked Questions (FAQ)

Why does my time look off by 8 hours?

Likely a timezone mismatch. Your timestamp is UTC, but you’re displaying it as local without specifying timezone or the viewer is in a different timezone. Always store UTC, display in the user’s timezone.

Should I use seconds or milliseconds?

Seconds are sufficient for most backend systems. Milliseconds are common in JavaScript and real-time UIs. Be consistent across services and document your precision.

How to handle DST jumps?

Use UTC internally, convert to local only for display. Avoid scheduling logic in local time around DST boundaries; if necessary, use libraries and authoritative tz data.

How to serialize time in APIs?

Prefer ISO 8601 strings with explicit timezone (e.g., Z for UTC) and include a Unix timestamp field for machine processing. Provide both when possible.

This guide helps you comprehensively understand Unix timestamp concepts and applications. If you have any questions or suggestions, feel free to contact us.