What Are Unix Timestamps?


What Are Unix Timestamps?


title-post

Understanding Unix Timestamps, what are they && why are they used?"

This is a brief to the point explenation on what Unix Timestamps are and why they are so prevalent within the coding space.

  payload: {
    sub: 'example-object-containing-unix-timestamps',
    iss: 'Ynot',
    exp: 1735080201,
    iat: 1735076601
  },


What Are Unix Timestamps?

A Unix timestamp (also called a POSIX timestamp or epoch time) is the number of seconds that have elapsed since January 1, 1970, at 00:00:00 UTC (the “Unix epoch”).

It is typically stored as an integer and is widely used in computing for date and time operations.

|
Online conversion tool

Why Are Timestamps Used?

Unix timestamps are used extensively in computing for the following reasons:

- **Simplicity**: They are _just integers_, which are easier for computers to store, compare, and manipulate.

- **Timezone-agnostic**: Unix timestamps are always in UTC, which _eliminates timezone-related complexities_.

- **Efficiency**: Storing time as a simple integer is _highly efficient in terms of memory usage and processing time_.

Current Time Jscipt

Within various applications and coding environments it’s highly practical and usefull to fetch the current time within the Unix Timestamp format.

const currentTime = Math.floor(Date.now() / 1000);

Practical Uses

Authentication Tokens: The iat and exp fields are commonly used in security tokens like JWT (JSON Web Tokens) to specify when a token was issued and when it will expire.

Logging: In log files, Unix timestamps help in tracking events over time in a format that is easy to sort, query, and analyze.

File Modification Times: Timestamps are often used to track when files or records were created, modified, or deleted.

Time Comparisson Comparing time’s for logic purposes within a application is wayy easier with Unix-Timestamps. No need for timezone bs :slight_smile:

Converting postgres-time to epoch-time

This is usefull information to know, as when working with postgreSQL databases you will often use postgreSQL default methods/types on db columns. For example the defaultNow() .

| So knowing how, and why to convert these string formatted to epoch-timestamp is highly usefull ^^ _


  • PostgreSQL Column
last_failed_attempt: timestamp('last_failed_attempt').defaultNow(), // Timestamp of last failed attempt
  • Jscript Code
const lastFailedAttemptUnixTimestamp = Math.floor(new Date(result[0].last_failed_attempt!).getTime() / 1000);

1. PostgreSQL stores timestamps in a format like YYYY-MM-DD HH:MM:SS . When you retrieve a timestamp from PostgreSQL, it’s by default in the JavaScript Date object format. For example:

"2025-01-10 15:42:00"

2. new Date(result[0].last_failed_attempt!)

The new Date() constructor in JavaScript accepts a date string or timestamp as an argument. When you pass a valid string (e.g., 2025-01-10 15:42:00), JavaScript parses it into a Date object, which internally represents the date and time as the number of milliseconds since January 1, 1970 (the Unix Epoch).

const date = new Date("2025-01-10 15:42:00");
console.log(date);  
// Outputs something like: "Thu Jan 10 2025 15:42:00 GMT+0000 (UTC)"

In this case, new Date(result[0].last_failed_attempt!) creates a Date object from the PostgreSQL timestamp value.

3. .getTime()

The .getTime() method on a Date object returns the number of milliseconds since January 1, 1970.

const milliseconds = date.getTime();  
console.log(milliseconds);  // For example: 1704898800000

The value returned by getTime() is the timestamp in milliseconds, which is the standard format used by JavaScript.

4. Math.floor()

Since Unix Epoch time traditionally represents time in seconds (not milliseconds), you need to convert the milliseconds to seconds by dividing by 1000. However, because .getTime() returns a floating point number (in case of fractional milliseconds), you use Math.floor() to ensure that you get the whole number part, truncating ( eliminating ) any potential fractional values.

const epochTime = Math.floor(milliseconds / 1000);  // Convert milliseconds to seconds
console.log(epochTime);  // Outputs: 1704898800

5. Final Result:

So, putting everything together:

const lastFailedAttemptUnixTimestamp = Math.floor(new Date(result[0].last_failed_attempt!).getTime() / 1000);
  • new Date(result[0].last_failed_attempt!): Creates a Date object from the PostgreSQL timestamp.
  • .getTime(): Converts the Date object into milliseconds since the Unix Epoch.
  • / 1000: Converts the milliseconds to seconds.
  • Math.floor(): Ensures the timestamp is an integer by discarding any fractional part.

This converts a PostgreSQL timestamp to Unix Epoch time (seconds since January 1, 1970).

Summary

  • The numbers 1735080201 and 1735076601 are Unix timestamps, which represent seconds elapsed since January 1, 1970, 00:00:00 UTC.

These timestamps are widely used in software, logging, security tokens, and APIs because they are simple, efficient, and timezone-independent. Now that you know what they are and why we use them. I am sure you can think of a way you’d apply them within you’re projects!

All Done :slight_smile:

1 Like