How to Use Timestamps and Time Units in JSDate

技流山

time unit
timestamp
2025-09-17
How to Use Timestamps and Time Units in JSDate

How to Use JSDate for Timestamps and Time Units

JSDate is a JavaScript library that makes working with dates and times easier. It handles timestamps (numbers representing time) and time units (like seconds or hours) better than the standard JavaScript Date object.

Getting Current Timestamps

Use JSDate.now() to get the current time as a timestamp. This gives you milliseconds since January 1, 1970 (Unix epoch).

const now = JSDate.now(); // Returns milliseconds

Convert milliseconds to seconds:

const seconds = Math.floor(JSDate.now() / 1000);

Creating Dates from Timestamps

Turn a timestamp back into a readable date:

const date = JSDate.fromTimestamp(1625097600000);

Working with Time Units

JSDate provides simple methods for time unit conversions:

// Convert hours to minutes
const minutes = JSDate.hours(2).toMinutes(); // Returns 120

// Add 30 minutes to current time
const later = JSDate.now().addMinutes(30);

Formatting Timestamps

Convert timestamps to human-readable formats:

JSDate.fromTimestamp(1625097600000).format('YYYY-MM-DD'); // "2021-06-30"

Timezone Handling

Work with different timezones easily:

const nyTime = JSDate.now().setTimezone('America/New_York');

Common Operations

Calculate time differences:

const start = JSDate.now();
// ...some operation...
const duration = JSDate.now().diff(start); // Milliseconds

Convert duration to minutes:

const minutes = duration.toMinutes();

JSDate simplifies these common tasks with clean, chainable methods that are easier to read than native JavaScript date operations. The library handles edge cases like daylight saving time and leap years automatically.