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

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

How to Convert Date Format to different pattern in Java

问题

以下是您要求的翻译内容:

我想要将日期格式从这种格式转换:EEE MMM dd HH:mm:ss zzz yyyy

转换成这种格式:yyyy-MM-dd

这是我从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"
}

我想要将startDateendDate转换成下面的JSON格式:

我想要的JSON输出:

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

到目前为止,我尝试了,但是失败了...
显示错误如下:
failed Unparseable date: \"2019-09-02\

并且这是我的代码:

Banner.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

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

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;
}

所以,我需要解决方案,应该怎么做?

英文:

I want to convert Date Format from this EEE MMM dd HH:mm:ss zzz yyyy

to like this yyyy-MM-dd

this is my data json right know from redis

{
   "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

and json ouput that i want

{
   "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\

.

and this is my code

Banner.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

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

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??

答案1

得分: 1

你可以使用 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);
// 输出结果为 2019-09-02

你也可以在 @JsonFormat(pattern = "yyyy-MM-dd") 中使用相同的方法。

英文:

you can use LocalDateTime for this , you should avoid using legacy Date class

 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")

答案2

得分: 1

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

[![Java中所有日期时间类型的表格包括现代和遗留][1]][1]

# *java.time*

您正在使用早些年被现代的 *java.time*在JSR 310中定义所取代的糟糕的日期时间类

[定义格式模式][2] 来匹配您的输入指定一个`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);

解析

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

将结果转储到控制台使用标准的 ISO 8601 格式生成文本明智地扩展标准以在方括号中添加时区的名称

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

>zdt = 2019-09-02T00:00+07:00[Asia/Jakarta]

您只想要日期不包括时间和时区信息

但您必须理解对于任何给定的时刻**日期会因时区而异**因此在某一时刻日本东京可能是明天”,而美国俄亥俄托莱多仍然是昨天”。

您想要印度尼西亚所见的日期吗

    LocalDate ld = zdt.toLocalDate();

还是想要UTC中所见的日期

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

然后生成您所需的输出字符串其格式恰好符合`LocalDate::toString`中默认使用的 ISO 8601 标准格式

    String output = ld.toString();

提示向您的数据发布者传达以下信息

 - 在交换日期时间值的文本时使用 [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) 标准来定义日期时间格式。
 - 通常在传达时刻时智慧之举是使用 [UTC][3]零小时--秒的偏移量),而不是特定的时区
 - 真实的时区名称采用 `大陆/地区` 的格式*不是* 2-4 个字母的伪时区`WIB`、`CST``IST`。 

  [1]: https://i.stack.imgur.com/iZm01.png
  [2]: https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/time/format/DateTimeFormatter.html#ofPattern(java.lang.String,java.util.Locale)
  [3]: https://en.wikipedia.org/wiki/Coordinated_Universal_Time
英文:

tl;dr

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

如何在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.

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.

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.

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

>zdt = 2019-09-02T00:00+07:00[Asia/Jakarta]

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?

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.

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.
  • The wisdom of generally communicating moments in UTC (an offset of zero hours-minutes-seconds) rather than a particular time zone.
  • Real time zone names are in the format of Continent/Region, not 2-4 letter pseudo-zones such as WIB, CST, or IST.

huangapple
  • 本文由 发表于 2020年3月16日 21:36:28
  • 转载请务必保留本文链接:https://go.coder-hub.com/60707021.html
匿名

发表评论

匿名网友

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

确定