Developer Code Snippets

Copy-paste code examples for working with dates and times

JavaScript
Python
Go
Rust
Java
C#
PHP
Ruby

Get Current Timestamp

Get the current Unix timestamp in seconds or milliseconds

// Current timestamp in milliseconds
const timestampMs = Date.now();
console.log(timestampMs); // 1705334400000

// Current timestamp in seconds
const timestampSec = Math.floor(Date.now() / 1000);
console.log(timestampSec); // 1705334400

// Using Date object
const date = new Date();
console.log(date.getTime()); // milliseconds

Convert Timestamp to Date

Convert a Unix timestamp to a readable date format

// From seconds
const timestampSec = 1705334400;
const dateFromSec = new Date(timestampSec * 1000);
console.log(dateFromSec.toISOString());
// 2024-01-15T12:00:00.000Z

// From milliseconds
const timestampMs = 1705334400000;
const dateFromMs = new Date(timestampMs);
console.log(dateFromMs.toLocaleString());

// Format options
const options = {
  weekday: 'long',
  year: 'numeric',
  month: 'long',
  day: 'numeric',
  hour: '2-digit',
  minute: '2-digit'
};
console.log(dateFromMs.toLocaleDateString('en-US', options));

Timezone Conversion

Convert between different timezones

const date = new Date();

// Convert to specific timezone
const options = {
  timeZone: 'America/New_York',
  year: 'numeric',
  month: 'long',
  day: 'numeric',
  hour: '2-digit',
  minute: '2-digit',
  timeZoneName: 'short'
};

console.log(date.toLocaleString('en-US', options));
// January 15, 2024 at 07:00 AM EST

// Multiple timezones
const timezones = ['America/New_York', 'Europe/London', 'Asia/Tokyo'];
timezones.forEach(tz => {
  console.log(`${tz}: ${date.toLocaleString('en-US', { timeZone: tz })}`);
});

Tips & Best Practices

Always use UTC for storage

Store timestamps in UTC and convert to local time only for display.

Use ISO 8601 format

When exchanging dates as strings, use ISO 8601 format for consistency.

Handle DST transitions

Be aware of daylight saving time when scheduling recurring events.

Use timezone libraries

Don't manually calculate timezone offsets - use proper libraries.