Java 8 计算两个区域之间的日期和时间差

x33g5p2x  于10个月前 转载在 Java  
字(1.3k)|赞(0)|评价(0)|浏览(110)

在 Java 8 中,我们可以使用 LocalDateTime.now(ZoneId.*of([[$2$]] zoneId)*) 获取 *zoneId * 的当前 LocalDateTime 实例,并使用 Duration 来计算两个 LocalDateTime 之间的差异。

Java8ZoneDiff.java

package org.websparrow;

import java.time.Duration;
import java.time.LocalDateTime;
import java.time.ZoneId;

public class Java8ZoneDiff {

	public static void main(String[] args) {

		// Current date & time of India
		LocalDateTime india = LocalDateTime.now(ZoneId.of("Asia/Kolkata"));

		// Current date & time of Thailand
		LocalDateTime thailand = LocalDateTime.now(ZoneId.of("Asia/Bangkok"));

		System.out.println("Thailand current date & time: " + thailand);
		System.out.println("India current date & time: " + india);
		System.out.println("\n================  Difference  ================\n");

		Duration diff = Duration.between(india, thailand);

		// days between Thailand and India
		System.out.println("Days: " + diff.toDays());

		// hours between Thailand and India
		System.out.println("Hours: " + diff.toHours());

		// Minutes between Thailand and India
		System.out.println("Minutes: " + diff.toMinutes());

		// Seconds between Thailand and India
		System.out.println("Seconds: " + diff.getSeconds());

	}
}

输出:

Thailand current date & time: 2020-07-02T22:55:08.968
India current date & time: 2020-07-02T21:25:08.968

================  Difference  ================

Days: 0
Hours: 1
Minutes: 90
Seconds: 5400

相关文章

热门文章

更多