使用 java.text.SimpleDateFormat 用可能的个位数月/日/小时解析日期

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3936473/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-30 04:01:56  来源:igfitidea点击:

Parse date with possible single-digit month/day/hour using java.text.SimpleDateFormat

javaparsingdatetimetalend

提问by ewall

On a project with Talend Open Studio (an Open Source code-generating ETL tool), I am getting errors parsing incoming date strings like "3/14/1967 0:00:00" (note the single-digit month).

在使用 Talend Open Studio(一种开源代码生成 ETL 工具)的项目中,我在解析传入日期字符串时遇到错误,例如“3/14/1967 0:00:00”(注意单位数月份)。

Digging into thecode, I can see it is using java.text.SimpleDateFormat. So the date pattern string I expect I need to use is "d-M-yyyy H:mm:ss"... but it keeps giving me errors like "Unparseable date: 3/14/1967 0:00:00".

深入研究代码,我可以看到它正在使用java.text.SimpleDateFormat。所以我希望我需要使用的日期模式字符串是“dM-yyyy H:mm:ss”……但它不断给我错误,比如“无法解析的日期:3/14/1967 0:00:00”。

I assume that SimpleDateFormat candeal with the single-or-double digit problem. Do I need a different date pattern?(Sure, I could do pre-processing to tweak the values before Java attempts to read the strings as Dates, but it shouldn't be necessary!)

我假设 SimpleDateFormat可以处理一位或两位数字的问题。我需要不同的日期模式吗?(当然,我可以在 Java 尝试将字符串读取为日期之前进行预处理以调整值,但这不是必需的!)

回答by Jon Skeet

Are you sure you actuallyneed to use d-M-yyyyrather than M/d/yyyy? I can see why it would have a problem with "3/14/1967"... what date did you expect that to be? Note that not only have you got "d" and "M" the wrong way round, but you've also specified "-" instead of "/" as the separator.

你确定你真的需要使用d-M-yyyy而不是M/d/yyyy?我明白为什么“3/14/1967”会出现问题……你预计那是哪一天?请注意,您不仅将“d”和“M”弄错了,而且还指定了“-”而不是“/”作为分隔符。