Tutorial
JavaScript でタイムスタンプを変換する方法: 例を含む完全なチュートリアル
はじめに
JavaScript でのタイムスタンプの変換は、Web 開発者にとっての基本的なスキルです。 API、データベース、ユーザー インターフェイスのいずれを使用している場合でも、Unix タイムスタンプと人間が判読できる日付の間で変換する必要が頻繁にあります。このチュートリアルでは、知っておくべきことをすべて説明します。
何を学ぶか
- ✅ 現在のタイムスタンプを取得する
- ✅ タイムスタンプを日付オブジェクトに変換する
- ✅ Date オブジェクトをタイムスタンプに変換する
- ✅ 表示用のタイムスタンプのフォーマット
- ✅ 異なるタイムスタンプ精度の処理
- ✅ タイムゾーンの操作
- ✅ よくある落とし穴とその回避方法
前提条件
必要なのは JavaScript の基本的な知識だけです。このチュートリアルには外部ライブラリは必要ありません (ただし、最後にいくつかの人気のあるライブラリについて触れます)。
ステップ 1: 現在のタイムスタンプを取得する
最も単純な操作 - 現在時刻をタイムスタンプとして取得します。
方法 1: Date.now() (推奨)
// Get current timestamp in milliseconds
const timestamp = Date.now();
console.log(timestamp);
// Output: 1704067200000 (13 digits)
これを使用する理由
- ✅最速の方法
- ✅ Date オブジェクトを作成する必要はありません
- ✅ 最も一般的に使用される
方法 2: new Date().getTime()
// Create Date object and get timestamp
const timestamp = new Date().getTime();
console.log(timestamp);
// Output: 1704067200000 (13 digits)
これをいつ使用しますか?
- すでにDateオブジェクトを持っている場合
- メソッドをチェーンする必要がある場合
方法 3: 単項プラス演算子
// Shorthand using unary plus
const timestamp = +new Date();
console.log(timestamp);
// Output: 1704067200000 (13 digits)
これをいつ使用しますか?
- ゴルフのコーディングや簡潔さが重要な場合
- 初心者にはお勧めしません(読みにくい)
タイムスタンプを数秒で取得する
JavaScript はデフォルトでミリ秒を使用しますが、多くの API は秒を使用します。
// Get timestamp in seconds (10 digits)
const timestampInSeconds = Math.floor(Date.now() / 1000);
console.log(timestampInSeconds);
// Output: 1704067200 (10 digits)
// Alternative: Using parseInt
const timestampSec = parseInt(Date.now() / 1000);
console.log(timestampSec);
// Output: 1704067200
ステップ 2: タイムスタンプを日付に変換する
Unix タイムスタンプを JavaScript Date オブジェクトに変換します。
基本的な変換
// Millisecond timestamp (13 digits)
const timestamp = 1704067200000;
const date = new Date(timestamp);
console.log(date);
// Output: Mon Jan 01 2024 00:00:00 GMT+0000 (UTC)
console.log(date.toISOString());
// Output: 2024-01-01T00:00:00.000Z
2 番目のタイムスタンプの変換
多くの API は、タイムスタンプをミリ秒ではなく秒 (10 桁) で返します。
// Second timestamp (10 digits) - MUST multiply by 1000!
const timestampInSeconds = 1704067200;
const date = new Date(timestampInSeconds * 1000);
console.log(date.toISOString());
// Output: 2024-01-01T00:00:00.000Z
⚠️ よくある間違い:
// ❌ WRONG: Using seconds directly
const wrongDate = new Date(1704067200);
console.log(wrongDate.toISOString());
// Output: 1970-01-20T17:27:47.200Z (WRONG!)
// ✅ CORRECT: Multiply by 1000
const correctDate = new Date(1704067200 * 1000);
console.log(correctDate.toISOString());
// Output: 2024-01-01T00:00:00.000Z (CORRECT!)
タイムスタンプの精度の検出
タイムスタンプが秒単位かミリ秒単位かを自動的に検出するヘルパー関数:
function createDateFromTimestamp(timestamp) {
// If timestamp has 10 digits, it's in seconds
// If timestamp has 13 digits, it's in milliseconds
const digitCount = timestamp.toString().length;
if (digitCount === 10) {
// Seconds - multiply by 1000
return new Date(timestamp * 1000);
} else if (digitCount === 13) {
// Milliseconds - use directly
return new Date(timestamp);
} else {
throw new Error(`Invalid timestamp: ${timestamp}`);
}
}
// Usage
const date1 = createDateFromTimestamp(1704067200); // 10 digits (seconds)
const date2 = createDateFromTimestamp(1704067200000); // 13 digits (milliseconds)
console.log(date1.toISOString()); // 2024-01-01T00:00:00.000Z
console.log(date2.toISOString()); // 2024-01-01T00:00:00.000Z
ステップ 3: 日付をタイムスタンプに変換する
JavaScript Date オブジェクトを Unix タイムスタンプに変換します。
現在の日付から
const now = new Date();
// Get timestamp in milliseconds
const timestampMs = now.getTime();
console.log(timestampMs); // 1704067200000
// Get timestamp in seconds
const timestampSec = Math.floor(now.getTime() / 1000);
console.log(timestampSec); // 1704067200
特定の日付文字列から
// ISO 8601 format (recommended)
const date1 = new Date('2024-01-01T00:00:00Z');
console.log(date1.getTime()); // 1704067200000
// Different date formats
const date2 = new Date('January 1, 2024');
const date3 = new Date('01/01/2024');
const date4 = new Date('2024-01-01');
console.log(date2.getTime()); // Depends on local timezone
console.log(date3.getTime()); // Depends on local timezone
console.log(date4.getTime()); // Usually 00:00:00 in local timezone
⚠️ 重要: 日付文字列形式が異なると、タイムゾーンに応じて動作も異なります。
開始日コンポーネント
// Create date from year, month, day, etc.
// Note: Month is 0-indexed (0 = January, 11 = December)
const date = new Date(2024, 0, 1, 0, 0, 0); // Jan 1, 2024, 00:00:00
const timestamp = date.getTime();
console.log(timestamp); // Local timezone timestamp
// For UTC, use Date.UTC()
const utcTimestamp = Date.UTC(2024, 0, 1, 0, 0, 0);
console.log(utcTimestamp); // 1704067200000 (UTC)
ステップ 4: タイムスタンプのフォーマット
タイムスタンプを人間が判読できる形式に変換します。
組み込みの JavaScript メソッド
const date = new Date(1704067200000);
// ISO 8601 format (best for APIs)
console.log(date.toISOString());
// Output: "2024-01-01T00:00:00.000Z"
// Locale-specific date string
console.log(date.toLocaleDateString());
// Output: "1/1/2024" (US) or "01/01/2024" (UK)
// Locale-specific date and time
console.log(date.toLocaleString());
// Output: "1/1/2024, 12:00:00 AM"
// Locale-specific time
console.log(date.toLocaleTimeString());
// Output: "12:00:00 AM"
// Full date string
console.log(date.toDateString());
// Output: "Mon Jan 01 2024"
// UTC string
console.log(date.toUTCString());
// Output: "Mon, 01 Jan 2024 00:00:00 GMT"
カスタム書式設定
function formatTimestamp(timestamp, format = 'full') {
const date = new Date(timestamp);
const year = date.getFullYear();
const month = String(date.getMonth() + 1).padStart(2, '0');
const day = String(date.getDate()).padStart(2, '0');
const hours = String(date.getHours()).padStart(2, '0');
const minutes = String(date.getMinutes()).padStart(2, '0');
const seconds = String(date.getSeconds()).padStart(2, '0');
const formats = {
'full': `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`,
'date': `${year}-${month}-${day}`,
'time': `${hours}:${minutes}:${seconds}`,
'short': `${month}/${day}/${year}`,
'iso': date.toISOString()
};
return formats[format] || formats.full;
}
// Usage
const timestamp = 1704067200000;
console.log(formatTimestamp(timestamp, 'full')); // "2024-01-01 00:00:00"
console.log(formatTimestamp(timestamp, 'date')); // "2024-01-01"
console.log(formatTimestamp(timestamp, 'time')); // "00:00:00"
console.log(formatTimestamp(timestamp, 'short')); // "01/01/2024"
Intl.DateTimeFormat の使用 (最新のアプローチ)
const timestamp = 1704067200000;
const date = new Date(timestamp);
// US English format
const usFormatter = new Intl.DateTimeFormat('en-US', {
year: 'numeric',
month: 'long',
day: 'numeric',
hour: '2-digit',
minute: '2-digit'
});
console.log(usFormatter.format(date));
// Output: "January 1, 2024 at 12:00 AM"
// Custom format
const customFormatter = new Intl.DateTimeFormat('en-US', {
weekday: 'long',
year: 'numeric',
month: 'short',
day: 'numeric',
hour: '2-digit',
minute: '2-digit',
second: '2-digit',
timeZoneName: 'short'
});
console.log(customFormatter.format(date));
// Output: "Monday, Jan 1, 2024, 12:00:00 AM UTC"
ステップ 5: タイムゾーンの操作
タイムスタンプを正確に変換するには、異なるタイムゾーンを処理することが重要です。
UTC と現地時間
const timestamp = 1704067200000; // Jan 1, 2024, 00:00:00 UTC
const date = new Date(timestamp);
// Get UTC components
console.log('UTC Year:', date.getUTCFullYear()); // 2024
console.log('UTC Month:', date.getUTCMonth() + 1); // 1
console.log('UTC Date:', date.getUTCDate()); // 1
console.log('UTC Hours:', date.getUTCHours()); // 0
// Get local components (depends on your timezone)
console.log('Local Year:', date.getFullYear()); // 2024
console.log('Local Month:', date.getMonth() + 1); // 1 (or different)
console.log('Local Date:', date.getDate()); // 1 (or different)
console.log('Local Hours:', date.getHours()); // 0 (or different)
特定のタイムゾーンへの変換
const timestamp = 1704067200000;
const date = new Date(timestamp);
// Display in different timezones using Intl.DateTimeFormat
const timezones = ['America/New_York', 'Europe/London', 'Asia/Tokyo'];
timezones.forEach(tz => {
const formatter = new Intl.DateTimeFormat('en-US', {
timeZone: tz,
year: 'numeric',
month: '2-digit',
day: '2-digit',
hour: '2-digit',
minute: '2-digit',
second: '2-digit',
timeZoneName: 'short'
});
console.log(`${tz}:`, formatter.format(date));
});
// Output:
// America/New_York: 12/31/2023, 07:00:00 PM EST
// Europe/London: 01/01/2024, 12:00:00 AM GMT
// Asia/Tokyo: 01/01/2024, 09:00:00 AM JST
タイムゾーン オフセット
const date = new Date();
// Get timezone offset in minutes
const offsetMinutes = date.getTimezoneOffset();
console.log('Offset in minutes:', offsetMinutes); // e.g., -480 for UTC+8
// Convert to hours
const offsetHours = -offsetMinutes / 60;
console.log('Offset in hours:', offsetHours); // e.g., 8 for UTC+8
// Format offset as string
const sign = offsetHours >= 0 ? '+' : '-';
const hours = String(Math.abs(Math.floor(offsetHours))).padStart(2, '0');
const minutes = String(Math.abs((offsetHours % 1) * 60)).padStart(2, '0');
console.log(`UTC${sign}${hours}:${minutes}`); // e.g., "UTC+08:00"
ステップ 6: よくある落とし穴と解決策
落とし穴 1: 秒とミリ秒
// ❌ WRONG: Assuming all timestamps are in milliseconds
const wrongDate = new Date(1704067200); // Treats as milliseconds
console.log(wrongDate.toISOString()); // 1970-01-20T17:27:47.200Z (WRONG!)
// ✅ CORRECT: Check and convert properly
const secondsTimestamp = 1704067200;
const correctDate = new Date(secondsTimestamp * 1000);
console.log(correctDate.toISOString()); // 2024-01-01T00:00:00.000Z (CORRECT!)
落とし穴 2: 月のインデックスはゼロです
// ❌ WRONG: Using 1-12 for months
const wrongDate = new Date(2024, 1, 1); // Creates Feb 1, not Jan 1
console.log(wrongDate.toDateString()); // Thu Feb 01 2024
// ✅ CORRECT: Use 0-11 for months
const correctDate = new Date(2024, 0, 1); // Creates Jan 1
console.log(correctDate.toDateString()); // Mon Jan 01 2024
落とし穴 3: 日付文字列のタイムゾーンの問題
// Different string formats behave differently!
// ISO 8601 with 'Z' - always UTC
const utcDate = new Date('2024-01-01T00:00:00Z');
console.log(utcDate.toISOString()); // 2024-01-01T00:00:00.000Z
// ISO 8601 without 'Z' - treated as local timezone
const localDate = new Date('2024-01-01T00:00:00');
console.log(localDate.toISOString()); // Depends on your timezone
// Date-only format - treated as local timezone at midnight
const dateOnly = new Date('2024-01-01');
console.log(dateOnly.toISOString()); // Usually local midnight
// ✅ BEST PRACTICE: Always use ISO 8601 with 'Z' for UTC
const safeDate = new Date('2024-01-01T00:00:00.000Z');
落とし穴 4: 無効な日付
// Invalid dates can cause silent errors
const invalidDate = new Date('not a date');
console.log(invalidDate); // Invalid Date
console.log(invalidDate.getTime()); // NaN
// ✅ BEST PRACTICE: Always validate
function isValidDate(date) {
return date instanceof Date && !isNaN(date.getTime());
}
const date1 = new Date('2024-01-01');
const date2 = new Date('invalid');
console.log(isValidDate(date1)); // true
console.log(isValidDate(date2)); // false
ステップ 7: 実践的な例
例 1: 「過去」形式で表示する
function timeAgo(timestamp) {
const now = Date.now();
const secondsAgo = Math.floor((now - timestamp) / 1000);
if (secondsAgo < 60) {
return `${secondsAgo} seconds ago`;
} else if (secondsAgo < 3600) {
const minutes = Math.floor(secondsAgo / 60);
return `${minutes} minute${minutes > 1 ? 's' : ''} ago`;
} else if (secondsAgo < 86400) {
const hours = Math.floor(secondsAgo / 3600);
return `${hours} hour${hours > 1 ? 's' : ''} ago`;
} else {
const days = Math.floor(secondsAgo / 86400);
return `${days} day${days > 1 ? 's' : ''} ago`;
}
}
// Usage
console.log(timeAgo(Date.now() - 30000)); // "30 seconds ago"
console.log(timeAgo(Date.now() - 300000)); // "5 minutes ago"
console.log(timeAgo(Date.now() - 7200000)); // "2 hours ago"
console.log(timeAgo(Date.now() - 172800000)); // "2 days ago"
例 2: API 応答ハンドラー
// Typical API response with timestamps
const apiResponse = {
created_at: 1704067200, // Seconds
updated_at: 1704153600000, // Milliseconds (mixed precision!)
expires_at: "2024-01-10T00:00:00Z" // ISO 8601 string
};
// Convert all to Date objects
function parseApiTimestamps(response) {
return {
created: new Date(response.created_at * 1000), // Convert seconds
updated: new Date(response.updated_at), // Already milliseconds
expires: new Date(response.expires_at) // Parse ISO string
};
}
const dates = parseApiTimestamps(apiResponse);
console.log('Created:', dates.created.toLocaleDateString());
console.log('Updated:', dates.updated.toLocaleDateString());
console.log('Expires:', dates.expires.toLocaleDateString());
例 3: 日付範囲バリデーター
function isWithinRange(timestamp, startDate, endDate) {
const date = new Date(timestamp);
const start = new Date(startDate);
const end = new Date(endDate);
return date >= start && date <= end;
}
// Usage
const eventTimestamp = 1704067200000; // Jan 1, 2024
const rangeStart = '2024-01-01';
const rangeEnd = '2024-12-31';
console.log(isWithinRange(eventTimestamp, rangeStart, rangeEnd)); // true
高度な使用例向けの人気のあるライブラリ
運用アプリケーションの場合は、次のライブラリを検討してください。
date-fns (推奨)
import { format, parseISO, formatDistance } from 'date-fns';
// Format timestamp
const timestamp = 1704067200000;
const formatted = format(timestamp, 'PPP');
console.log(formatted); // "Jan 1st, 2024"
// Time ago
const distance = formatDistance(timestamp, Date.now(), { addSuffix: true });
console.log(distance); // "2 days ago"
ルクソン (モダン、タイムゾーン対応)
import { DateTime } from 'luxon';
// From timestamp
const dt = DateTime.fromMillis(1704067200000);
console.log(dt.toISO()); // "2024-01-01T00:00:00.000Z"
// Timezone conversion
const tokyo = dt.setZone('Asia/Tokyo');
console.log(tokyo.toFormat('yyyy-MM-dd HH:mm:ss'));
概要
次の方法を学びました。
- ✅
Date.now()で現在のタイムスタンプを取得します - ✅ タイムスタンプを日付オブジェクトに変換します
- ✅ Date オブジェクトをタイムスタンプに変換します。
- ✅ 表示用の日付の書式設定
- ✅ 異なるタイムスタンプ精度を処理します
- ✅ タイムゾーンを操作する
- ✅ よくある落とし穴を回避する
関連ツール
無料ツールを使用して学んだことを実践してください。
- Unix タイムスタンプ コンバータ - 対話型タイムスタンプ変換
- 現在のタイムスタンプ - 現在の時刻をさまざまな形式で取得します
- JavaScript タイムスタンプ ヘルパー - JavaScript 固有のツール
- バッチタイムスタンプコンバータ - 複数のタイムスタンプを変換します
次のステップ
- タイムスタンプの精度レベル について学習します。
- タイムゾーンを理解する を探索します。
- [2038 年問題] について読む(/guides/year-2038-問題)
最終更新日: 2025 年 1 月