英文:
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);
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论