简体   繁体   English

如何在 Java 中将日期格式转换为不同的模式

[英]How to Convert Date Format to different pattern in Java

I want to convert Date Format from this EEE MMM dd HH:mm:ss zzz yyyy我想从此EEE MMM dd HH:mm:ss zzz yyyy转换日期格式

to like this yyyy-MM-dd喜欢这个yyyy-MM-dd

this is my data json right know from redis这是我从 redis 知道的数据 json

{
   "bannerId":4,
   "bannerName":"banner test test 2 123"
   "startDate":"Mon Sep 02 00:00:00 WIB 2019",
   "endDate":"Sat Sep 28 00:00:00 WIB 2019"
}

and i want to convert startDate and endDate like json below我想像下面的json一样转换startDateendDate

and json ouput that i want和我想要的 json 输出

{
   "bannerId":4,
   "bannerName":"banner test test 2 123"
   "startDate":"2019-09-02",
   "endDate":"2019-09-28"
}

so far I've tried it, but failed.. show error like this failed Unparseable date: \\"2019-09-02\\到目前为止,我已经尝试过,但失败了.. 显示错误,例如failed Unparseable date: \\"2019-09-02\\

. .

and this is my code这是我的代码

Banner.java横幅.java

@Getter @Setter @NoArgsConstructor
public class Banner {

    private Integer bannerId;
    private String bannerName;

    @JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "EEE MMM dd HH:mm:ss zzz yyyy", timezone = "Asia/Jakarta")
    private Date startDate;
    @JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "EEE MMM dd HH:mm:ss zzz yyyy", timezone = "Asia/Jakarta")
    private Date endDate;
}

BannerController.java横幅控制器.java

DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
listRedis = bannerService.loadBannerRedis(Constant.DVC_BANNER_MOBILE, Constant.LOC_BANNER_HOME, Constant.PST_BANNER_MAIN);
    for (Banner banner : listRedis) {

         banner.setStartDate(
              new SimpleDateFormat("yyyy-MM-dd").parse(
                  Convert.convertDate(dateFormat.format(banner.getStartDate()))));
    }

Convert.java转换.java

public static String convertDate(String dd) throws ParseException {
        DateFormat formatter = new SimpleDateFormat("EEE MMM dd HH:mm:ss zzz yyyy");
        Date date = (Date)formatter.parse(dd);     

        Calendar cal = Calendar.getInstance();
        cal.setTime(date);
        String formatedDate = cal.get(Calendar.YEAR) + "-" + (cal.get(Calendar.MONTH) + 1) + "-" + cal.get(Calendar.DATE);
        return formatedDate;
}

so, i need solution what im to do??所以,我需要解决我该怎么办??

you can use LocalDateTime for this , you should avoid using legacy Date class您可以为此使用LocalDateTime ,您应该避免使用旧的Date

 String str = "Mon Sep 02 00:00:00 WIB 2019";
            LocalDateTime parse = LocalDateTime.parse(str, DateTimeFormatter.ofPattern("EEE MMM dd HH:mm:ss zzz yyyy"));
            System.out.println(parse);
            DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
            String format = parse.format(dateTimeFormatter);
            System.out.println(format);  
            // out-put 2019-09-02

You can also use same on @JsonFormat(pattern = "yyyy-MM-dd")您也可以在@JsonFormat(pattern = "yyyy-MM-dd")上使用相同的

tl;dr tl;博士

ZonedDateTime
        .parse(
                "Mon Sep 02 00:00:00 WIB 2019" ,
                DateTimeFormatter.ofPattern( "EEE MMM dd HH:mm:ss z uuuu" , Locale.US )
        )
        .toLocalDate()

2019-09-02 2019-09-02

Java 中所有日期时间类型的表,包括现代的和传统的

java.time时间

You are using terrible date-time classes that were years ago supplanted by the modern java.time classes defined in JSR 310.您正在使用多年前被 JSR 310 中定义的现代java.time类取代的糟糕的日期时间类。

Define a formatting pattern to match your input. 定义格式模式以匹配您的输入。 Specify a Locale to determine the human language and cultural norms to use in parsing name of month, name of day, and so on.指定Locale以确定用于解析月份名称、日期名称等的人类语言和文化规范。

String input = "Mon Sep 02 00:00:00 WIB 2019";
Locale locale = Locale.US;
DateTimeFormatter f = DateTimeFormatter.ofPattern( "EEE MMM dd HH:mm:ss z uuuu" , locale );

Parse.解析。

ZonedDateTime zdt = ZonedDateTime.parse( input , f );

Dump to console, using standard ISO 8601 format for generated text, wisely extending the standard to append the name of the time zone in square brackets.转储到控制台,使用标准 ISO 8601 格式生成文本,明智地扩展标准以在方括号中附加时区名称。

System.out.println( "zdt = " + zdt );

zdt = 2019-09-02T00:00+07:00[Asia/Jakarta] zdt = 2019-09-02T00:00+07:00[亚洲/雅加达]

You want the date only, without time-of-day and without the time zone.您只需要日期,没有时间和时区。

But you must understand that for any given moment the date varies around the world by time zone.但是您必须明白,对于任何给定时刻,日期在世界各地因时区而异 So at any moment it can be "tomorrow" in Tokyo Japan while still "yesterday" in Toledo Ohio US.所以在任何时候,在日本东京都可能是“明天”,而在美国俄亥俄州托莱多仍然是“昨天”。

Do you want the date as seen in Indonesia?您想要在印度尼西亚看到的日期吗?

LocalDate ld = zdt.toLocalDate() ;

Or do you want the date as seen in UTC?或者你想要在UTC中看到的日期?

LocalDate ld = 
    zdt
    .toOffsetDateTime()
    .withOffsetSameInstant( ZoneOffset.UTC )
    .toLocalDate() 
;

Then generate your desired output string whose format happens to comply with the ISO 8601 standard format used by default in LocalDate::toString .然后生成所需的输出字符串,其格式恰好符​​合LocalDate::toString默认使用的 ISO 8601 标准格式。

String output = ld.toString() ;

Tip: Educate the publisher of your data about:提示:就以下方面对数据发布者进行教育:

  • The ISO 8601 standard defining date-time formats to use when exchanging date-time values as text. ISO 8601标准定义了在将日期时间值作为文本交换时使用的日期时间格式。
  • The wisdom of generally communicating moments in UTC (an offset of zero hours-minutes-seconds) rather than a particular time zone.通常以UTC (零时分秒的偏移量)而不是特定时区传达时刻的智慧。
  • Real time zone names are in the format of Continent/Region , not 2-4 letter pseudo-zones such as WIB , CST , or IST .实时区域名称采用Continent/Region格式,而不是2-4 个字母的伪区域,例如WIBCSTIST

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM