Hey,
DeepCode offers an AI based Static Program Analysis for Java, Javascript and Typescript, and Python. You might know, DeepCode uses thousands of open source repos to train our engine. We asked the engine team to provide some stats on the findings. On the top suggestions from our engine, we want to introduce and give some background in this series of blog articles. And this one made me dizzy as we are looking back on like 70 years of software engineering and still have problems with — drumroll — date formats…
语言:爪哇 缺陷:日期数据格式(类别常规1) 诊断:日期时间输出格式不明确(例如12h输出,不带am / pm后缀)
Background:
快速,日期格式字符串有什么区别MM-DD-YYYY和mm-dd-yyyy要么MM-dd-yyyy?? 我可以告诉你,当您在适当的时候呼叫它们时,它们都会得到相同的结果。 但显然,它们根本不同。 好吧,让我们阐明一下……
Java had a bad start regarding its date classes. java.util.Date
had serious design flaws when it was introduced which led to lots of confusion. A Date
instance in Java is actually not a date but a moment in time, therefore (1) it has no time zone, (2) no format, (3) no calendar system. I suggest this valuable blog post for the full story. After years, the Java community acted and introduced new classes. Still, there are lots of traps (for example, java.text.SimpleDateFormat
is not thread-safe while java.time.format.DateTimeFormatter
is) but for now, let us focus the most common mistake which is the one flagged by DeepCode:
- 使用毫米几个月和/或MM几分钟(错误!)。使用H对于“一天中的一小时”H原本是。H范围从0到23,而H ranges from 1 to 12 and is mostly used as single cHaracter. It needs tHe AM/PM information or it is ambiguous.使用YYYY for year. It is meant to be used in conjunction witH “week of tHe year” and can lead to unexpected results in tHe first and last week of a year. Normally, you want to use yyyy。使用DD for “day of tHe montH” but in reality, it means “day of tHe year”Make sure to use tHe correct pattern cHaracters. As a reference in Java, tHe following applies.
注意:ThisisJava.Donotsimplyexpectthistobethesameelsewhere.Alwayscheckthedocumentation.
对于日期和时间周围的问题,这不是穷尽的。 我们可以谈谈UTC偏移量和时区之间的差异,时区缩写周围的问题(是BST英国夏令时还是英国标准时间,还是布干维尔标准时间(不,我没有做这个)?嗯,谁知道),或者 不同地区的不同日历。 为了提供上述小难题的答案,您可能几乎总是想要MM-dd-yyyy。
铜
0xff