Java formatting GMT Date

Gus*_*sta 0 java calendar date

I'm not finding a way to do edit GMT Date

I receive "params.date" one string in this format "yyyyMMdd", so this is my flow:

Date date = new SimpleDateFormat('yyyyMMdd').parse(params.data)
System.out.println(sdf.parse(params.data))
Run Code Online (Sandbox Code Playgroud)

output:

Thu Nov 17 21:00:00 GMT-03:00 2022
Run Code Online (Sandbox Code Playgroud)

And I need it:

Thu Nov 17 21:00:00 GMT-00:00 2022
Run Code Online (Sandbox Code Playgroud)

Can someone help me?

Arv*_*ash 5

几个要点:

  1. Thu Nov 17 21:00:00 GMT-03:00 2022 不等于 Thu Nov 17 21:00:00 GMT-00:00 2022。 Thu Nov 17 21:00:00 GMT-03 的日期时间: 00 2022 等于 2022 年 11 月 18 日星期五 00:00:00 GMT+00:00 2022 的日期时间,您可以通过在 2022 年 11 月 17 日星期四 21:00:00 GMT-03:00 2022 基础上加上 3 小时来获得该日期时间。
  2. 您的时区偏移量为 -03:00,因此该java.util.Date对象将以默认时区偏移量显示。请注意,它java.util.Date并不代表真实的日期时间,而是为您提供距纪元的毫秒数,然后实现Date#toString应用系统的时区来呈现字符串。
  3. java.util日期时间 API 及其格式化 APISimpleDateFormat过时且容易出错。建议完全停止使用它们并切换到现代日期时间 API

使用 java.time API 进行演示

import java.time.LocalDate;
import java.time.ZoneOffset;
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Locale;

public class Main {

        public static void main(String[] args) {
                String data = "20221118";
                LocalDate date = LocalDate.parse(data, DateTimeFormatter.BASIC_ISO_DATE);

                ZonedDateTime zdt1 = date.atStartOfDay(ZoneOffset.UTC);
                ZonedDateTime zdt2 = zdt1.withZoneSameInstant(ZoneOffset.of("-03:00"));

                DateTimeFormatter formatter = DateTimeFormatter.ofPattern("EEE MMM dd HH:mm:ss 'GMT'xxx uuuu",
                                Locale.ENGLISH);
                System.out.println(formatter.format(zdt2));
                System.out.println(formatter.format(zdt1));
        }
}
Run Code Online (Sandbox Code Playgroud)

输出

Thu Nov 17 21:00:00 GMT-03:00 2022
Fri Nov 18 00:00:00 GMT+00:00 2022
Run Code Online (Sandbox Code Playgroud)

从Trail: Date Time中了解有关现代日期时间 API 的更多信息。