Java日期时间相减

huangapple go评论63阅读模式
英文:

Java date time subtraction

问题

String date1 = "2020/05/08 16.38.37";
String date2 = "2020/04/08 20.18.10";

// 我希望在Java中从完整的date1中减去完整的date2(包括日期和时间),并以小时为单位获得结果。
// 如何进行?
英文:

String date1 = "2020/05/08 16.38.37"
String date2 = "2020/04/08 20.18.10"

I wish to subtract complete date1 with complete date2 (date and time both included) and get the result in hours in java .
How to proceed ?

答案1

得分: 2

知道两个给定时间戳之间相差多少小时是 不可能的,除非您告诉我在地球上的哪个位置要进行计算。例如,如果您问我在 01:30 和 03:30 之间相差多少分钟,答案似乎是 120,但是如果由于夏时制的原因恰好是时钟向前调整一小时的那个夜晚,实际正确的答案将是 60。

如果您从不想要这种调整,协调世界时(UTC)就不会像这样发生奇怪的调整,因此您始终可以选择在UTC时区进行计算。

因此,步骤如下:

  1. 解析您的字符串(它们表示“本地”日期/时间,因为它们根本不包含时区信息)为 LocalDateTime 对象。
  2. 将这两个对象放置在您选择的时区,将它们转换为 ZonedDateTime 对象。
  3. 现在询问API在这两者之间计算小时、分钟或者您更喜欢的任何单位。
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy/MM/dd HH.mm.ss");
ZoneId zone = ZoneId.of("Europe/Amsterdam");

LocalDateTime input1 = LocalDateTime.parse("2020/05/08 16.38.37", formatter);
LocalDateTime input2 = LocalDateTime.parse("2020/04/08 20.18.10", formatter);
ZonedDateTime zoned1 = input1.atZone(zone);
ZonedDateTime zoned2 = input2.atZone(zone);

Duration duration = Duration.between(zoned1, zoned2);

long hours = duration.toHours();
System.out.println(hours);

上述代码将输出 -716(也就是说,第一个时间戳至少在第二个时间戳之前 716 小时,但不足 717 小时,至少对于阿姆斯特丹的居民来说是这样)。

注:如果您想要讨论星期、月份等等,您需要使用 Period 而不是 Duration

英文:

Knowing how many hours are between 2 given timestamps is not possible unless you tell me where on the planet you want to do the math for. For example, if you ask me the minutes between 01:30 and 03:30, the answer would seem to be 120, but if due to daylight savings that so happens to be exactly the night where the clocks are moved an hour forward, the actual correct answer'd be 60.

If you never want that kind of adjustment, UTC doesn't 'suffer' from weird adjustments like this, so you can always elect to do the math in the UTC zone.

Thus, the steps:

  1. parse your strings (which represent 'local' date/times, given that they include no timezone info at all) into LocalDateTime objects.
  2. Zone these 2 objects by turning them into ZonedDateTime objects at a zone of your choosing.
  3. Now ask the API to calculate the hours, minutes, whichever one you prefer between the two.
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy/MM/dd HH.mm.ss");
ZoneId zone = ZoneId.of("Europe/Amsterdam");

LocalDateTime input1 = LocalDateTime.parse("2020/05/08 16.38.37", formatter);
LocalDateTime input2 = LocalDateTime.parse("2020/04/08 20.18.10", formatter);
ZonedDateTime zoned1 = input1.atZone(zone);
ZonedDateTime zoned2 = input2.atZone(zone);

Duration duration = Duration.between(zoned1, zoned2);

long hours = duration.toHours();
System.out.println(hours);

the above would print -716 (as in, the first stamp is at least 716 hours, and less than 717 hours, before the second.... at least, if you ask someone living in Amsterdam).

NB: If you want to talk about weeks, months, etc - you want Period and not Duration.

答案2

得分: 1

java.time

首先,在您的程序中不要将日期和时间保存为字符串。就像您不会使用字符串来保存数字和布尔值一样(我希望如此),您也不应该将日期和时间保存为字符串。请使用来自现代 Java 日期和时间 API 的适当日期和时间类型,即 java.time

假设您的日期和时间位于某个明确定义的时区,我建议使用 ZonedDateTime

ZoneId zone = ZoneId.of("America/Montreal");
ZonedDateTime dateTime1 = ZonedDateTime.of(2020, 5, 8, 16, 38, 37, 0, zone);
ZonedDateTime dateTime2 = ZonedDateTime.of(2020, 4, 8, 20, 18, 10, 0, zone);

找到时间差只需要一行代码:

long diffHours = ChronoUnit.HOURS.between(dateTime2, dateTime1);

System.out.println("Difference in hours: " + diffHours);

此示例代码片段的输出为:

Difference in hours: 716

请在我放置 "America/Montreal" 的位置插入您所需的时区。如果两个日期之间的转换到夏令时(DST)或从夏令时(DST)转换之间存在,选择不同的时区可能会导致我们多出或少了一个小时。

解析日期时间输入

如果您的日期和时间是字符串输入,您需要做的第一件事就是解析它们。以下是一个示例:

DateTimeFormatter inputFormatter = DateTimeFormatter.ofPattern("uuuu/MM/dd HH.mm.ss");

String string1 = "2020/05/08 16.38.37";
String string2 = "2020/04/08 20.18.10";

ZonedDateTime dateTime1 = LocalDateTime.parse(string1, inputFormatter).atZone(zone);
ZonedDateTime dateTime2 = LocalDateTime.parse(string2, inputFormatter).atZone(zone);

System.out.println("Date and time 1: " + dateTime1);
System.out.println("Date and time 2: " + dateTime2);

输出示例:

Date and time 1: 2020-05-08T16:38:37-04:00[America/Montreal]
Date and time 2: 2020-04-08T20:18:10-04:00[America/Montreal]

链接

Oracle 教程:日期时间,解释如何使用 java.time

英文:

java.time

First don’t keep your dates and times as strings in your program. Just as you don’t use strings for keeping your numbers and Boolean values (I hope), you shouldn’t for dates and times either. Use proper date and time types from java.time, the modern Java date and time API.

Assuming that your dates and times are in some well-defined time zone, I suggest using ZonedDateTime for them.

	ZoneId zone = ZoneId.of("America/Montreal");
	ZonedDateTime dateTime1 = ZonedDateTime.of(2020, 5, 8, 16, 38, 37, 0, zone);
	ZonedDateTime dateTime2 = ZonedDateTime.of(2020, 4, 8, 20, 18, 10, 0, zone);

Finding the difference is a one-liner:

	long diffHours = ChronoUnit.HOURS.between(dateTime2, dateTime1);
	
	System.out.println("Difference in hours: " + diffHours);

Output from this example snippet is:

> Difference in hours: 716

Please insert your desired time zone where I put America/Montreal. Choosing a different time zone may cause us to get an hour more or fewer if the transition to or from summer time (DST) lies between the two dates.

Parsing date-time input

If your dates and times are string input, the first thing you need to do with them is parse them. An example:

	DateTimeFormatter inputFormatter = DateTimeFormatter.ofPattern("uuuu/MM/dd HH.mm.ss");
	
	String string1 = "2020/05/08 16.38.37";
	String string2 = "2020/04/08 20.18.10";
			
	ZonedDateTime dateTime1 = LocalDateTime.parse(string1, inputFormatter).atZone(zone);
	ZonedDateTime dateTime2 = LocalDateTime.parse(string2, inputFormatter).atZone(zone);
	
	System.out.println("Date and time 1: " + dateTime1);
	System.out.println("Date and time 2: " + dateTime2);`

> Date and time 1: 2020-05-08T16:38:37-04:00[America/Montreal]
> Date and time 2: 2020-04-08T20:18:10-04:00[America/Montreal]

Oracle tutorial: Date Time explaining how to use java.time.

huangapple
  • 本文由 发表于 2020年5月30日 02:12:31
  • 转载请务必保留本文链接:https://go.coder-hub.com/62092271.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定