与格林威治标准时间的时区差异导致时间发生变化?

Timezone differences with GMT causing hours to change?

以下是我输入的日期字符串格式:

2025-08-08T15%3A41%3A46

我必须将上面的字符串日期转换成如下所示的格式:

Fri Aug 08 15:41:46 GMT-07:00 2025

我得到以下代码:

SimpleDateFormat dateParser = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss", Locale.US);
String decodedDate = URLDecoder.decode("2025-08-08T15%3A41%3A46", "UTF-8");
Date date = dateParser.parse(decodedDate);

//Decode the given date and convert to Date object
SimpleDateFormat sdf = new SimpleDateFormat("EEE MMM dd hh:mm:ss z yyyy", Locale.US);
sdf.setTimeZone(TimeZone.getTimeZone("GMT-07:00"));

System.out.println(sdf.format(date));

这是它在控制台上打印出来的内容。我不确定为什么它打印的小时值与我上面在所需输出中的值不同。它应该打印出 15 但它正在打印 03.

Fri Aug 08 03:41:46 GMT-07:00 2025

我不确定由于与格林威治标准时间的时区差异导致营业时间发生变化的原因是什么?

除了在第一种格式中您使用 "HH" 小时,即 "Hour in day (0-23)" 和第二种格式使用 "hh",即 "Hour in am/pm (1-12)" 外,这是相同的时间。

正如 正确指出的那样,您的格式设置模式使用了不正确的字符。

让我们看看另一种现代方法。

ISO 8601

您的输入字符串在解码以恢复 COLON 字符后,是标准 ISO 8601 格式。

URLDecoder.decode("2025-08-08T15%3A41%3A46", "UTF-8")

2025-08-08T15:41:46

使用java.time

您使用的是麻烦的旧日期时间 类,现在已被 java.time 类 取代。

java.time类在parsing/generating字符串时默认使用ISO 8601

您的输入字符串缺少任何与 UTC 或时区的偏移指示。所以我们解析为 LocalDateTime.

LocalDateTime ldt = LocalDateTime.parse( "2025-08-08T15:41:46" ) 

ldt.toString(): 2025-08-08T15:41:46

如果您知道预期的时区,请指定 ZoneId 以生成 ZonedDateTime

ZonedDateTime zdt = ldt.atZone( ZoneId.of( "America/Montreal" ) ) ;

zdt.toString(): 2025-08-08T15:41:46-04:00[America/Montreal]


关于java.time

java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.

Joda-Time project, now in maintenance mode, advises migration to the java.time 类.

要了解更多信息,请参阅 Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310

在哪里获取java.time类?

ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval, YearWeek, YearQuarter, and more.