時間の差を計算する方法
2 つの日付やタイムスタンプの間の期間を、さまざまな単位で計算します。
问题
2 つの日付の間にどれだけの時間が経過したかを、日・時間・分・秒の単位で知る必要があります。
前提条件
- タイムスタンプの理解
- 基本的な算術
ステップ
-
1. Convert both dates to a common unit
Parse both dates into Unix timestamps (milliseconds since epoch). This gives a common unit for subtraction. Ensure both dates are in the same timezone (UTC is recommended) to avoid off-by-hour errors.
入力2023-10-14 and 2023-10-10输出timestamps computed -
2. Subtract and convert to desired units
Subtract the earlier timestamp from the later one to get the difference in milliseconds. Convert to seconds (/1000), minutes (/60000), hours (/3600000), or days (/86400000). Account for the sign if the order is reversed.
入力4 days difference输出345600000 ms = 4 days -
3. Handle edge cases
Daylight Saving Time transitions can make a day 23 or 25 hours long. If you need calendar-day differences rather than 24-hour periods, use a date library that accounts for DST. Leap seconds are typically ignored by Unix time.
入力across DST boundary输出use calendar-aware library
期待される結果
2 つの日付の時間差を、指定した単位で表したもの。
よくあるエラー
- Off by one hour due to DST
- Use a timezone-aware date library for calendar calculations. Simple millisecond subtraction does not account for DST transitions.
- Negative duration
- The earlier date was subtracted from the later date. Use absolute value or ensure the order is correct.
トラブルシューティング指引
- If the difference is off by hours, check for timezone or DST issues.
- For human-readable durations (e.g., '2 days, 3 hours'), format the result after computing.
セキュリティ上の制限
- Time difference calculation is a pure computation with no security implications.