Utilities•8 min read
Date and Time Tools: Timestamps, Calculators, and Converters
Master date and time manipulation. Learn Unix timestamps, date calculations, timezone handling, and time conversions.
By Andy Pham
Date and Time Tools: Timestamps, Calculators, and Converters
Working with dates and times is a common programming task. Learn about timestamps, calculations, and conversions.
Unix Timestamps
What is a Unix Timestamp?
- Seconds since January 1, 1970 (UTC)
- Universal, timezone-independent
- Example: 1704067200 = January 1, 2024 00:00:00 UTC
JavaScript Timestamps
// Current timestamp (seconds)
const timestamp = Math.floor(Date.now() / 1000);
// From date to timestamp
const date = new Date('2024-01-01');
const ts = Math.floor(date.getTime() / 1000);
// From timestamp to date
const dateFromTs = new Date(timestamp * 1000);
Python Timestamps
import time
from datetime import datetime
# Current timestamp
timestamp = int(time.time())
# From datetime to timestamp
dt = datetime(2024, 1, 1)
ts = int(dt.timestamp())
# From timestamp to datetime
dt_from_ts = datetime.fromtimestamp(timestamp)
Date Calculations
Add/Subtract Days
function addDays(date, days) {
const result = new Date(date);
result.setDate(result.getDate() + days);
return result;
}
// 30 days from now
const futureDate = addDays(new Date(), 30);
// 30 days ago
const pastDate = addDays(new Date(), -30);
Days Between Dates
function daysBetween(date1, date2) {
const oneDay = 24 * 60 * 60 * 1000;
return Math.round(Math.abs((date1 - date2) / oneDay));
}
Business Days
function addBusinessDays(date, days) {
let result = new Date(date);
let added = 0;
while (added < days) {
result.setDate(result.getDate() + 1);
const dayOfWeek = result.getDay();
if (dayOfWeek !== 0 && dayOfWeek !== 6) {
added++;
}
}
return result;
}
Time Conversions
Unit Conversions
| From | To | Formula |
|---|---|---|
| Seconds | Minutes | / 60 |
| Minutes | Hours | / 60 |
| Hours | Days | / 24 |
| Days | Weeks | / 7 |
Timezone Handling
// Get timezone offset
const offset = new Date().getTimezoneOffset(); // minutes
// Convert to specific timezone
function toTimezone(date, tz) {
return new Date(date.toLocaleString('en-US', { timeZone: tz }));
}
const nyTime = toTimezone(new Date(), 'America/New_York');
const tokyoTime = toTimezone(new Date(), 'Asia/Tokyo');
Formatting Dates
JavaScript
const date = new Date();
// ISO format
date.toISOString(); // "2024-01-01T00:00:00.000Z"
// Locale format
date.toLocaleDateString('en-US'); // "1/1/2024"
date.toLocaleDateString('en-GB'); // "01/01/2024"
// Custom format with Intl
const formatter = new Intl.DateTimeFormat('en-US', {
year: 'numeric',
month: 'long',
day: 'numeric'
});
formatter.format(date); // "January 1, 2024"
Try Our DateTime Tools
Conclusion
Understanding date/time manipulation is crucial for scheduling, logging, and data processing.