从Java 11中的Date对象中移除时区/时间元素。

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

Remove timezone/time element from Date object in Java 11

问题

我有以下的字符串被获取:

> String dateStr = "Tue Dec 06 00:00:00 EDT 2002";

但是当我使用以下的DateFormat对象进行解析时,如下所示

DateFormat myDateFormat = new SimpleDateFormat("E MMM dd HH:mm:ss z yyyy");
Date myDate=myDateFormat.parse(dateStr);

即使我尝试格式化或解析结果的myDate对象,我仍然无法从结果的Date对象中删除时区/时间约束。

预期输出是仅为DD/MM/YYYY格式的Date对象。

英文:

I have below string being fetched:

> String dateStr = "Tue Dec 06 00:00:00 EDT 2002";

But when I am parsing using the below DateFormat object shown as below

 DateFormat myDateFormat = new SimpleDateFormat("E MMM dd HH:mm:ss z yyyy");
 Date myDate=dateFormatTime.parse(myDateFormat);

Even if I try to format or parse the resultant myDate object , I am not able to remove the timezone/time constraint from the resultant Date object.

Expected output is Date object of just DD/MM/YYYY format only.

答案1

得分: 2

1, 这个字符串存在不一致性。实际上,2002年12月6日是星期五,而不是星期二。字符串开头的 "Tue" 似乎是一个错误。

2, 较新的 java.time 包(在Java 8及更高版本中可用)提供了一个更强大的框架来处理日期和时间。

String dateStr = "Tue Dec 06 00:00:00 EDT 2002";

// 调整日期字符串以省略星期几。
dateStr = dateStr.substring(4);

DateTimeFormatter parseFormat = DateTimeFormatter.ofPattern("MMM dd HH:mm:ss z yyyy", Locale.US);
ZonedDateTime dateTime = ZonedDateTime.parse(dateStr, parseFormat);

DateTimeFormatter outputFormat = DateTimeFormatter.ofPattern("dd/MM/yyyy");
String outputDateStr = outputFormat.format(dateTime);

System.out.println(outputDateStr);
英文:

1, there's an inconsistency in this string. December 6, 2002, was actually a Friday, not a Tuesday. The "Tue" at the beginning of the string seems to be a mistake.

2, The newer java.time package (available in Java 8 and later) provides a more robust framework for handling date and time.

String dateStr = "Tue Dec 06 00:00:00 EDT 2002";

// Adjust the date string to omit the day of the week.
dateStr = dateStr.substring(4);

DateTimeFormatter parseFormat = DateTimeFormatter.ofPattern("MMM dd HH:mm:ss z yyyy", Locale.US);
ZonedDateTime dateTime = ZonedDateTime.parse(dateStr, parseFormat);

DateTimeFormatter outputFormat = DateTimeFormatter.ofPattern("dd/MM/yyyy");
String outputDateStr = outputFormat.format(dateTime);

System.out.println(outputDateStr);

huangapple
  • 本文由 发表于 2023年6月15日 14:28:24
  • 转载请务必保留本文链接:https://go.coder-hub.com/76479698.html
匿名

发表评论

匿名网友

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

确定