接受05/05/1999和5/5/1999等的日期时间解析 [英] Date time parsing that accepts 05/05/1999 and 5/5/1999, etc

查看:169
本文介绍了接受05/05/1999和5/5/1999等的日期时间解析的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否有一种简单的方法来解析可能是MM / DD / yyyy,M / D / yyyy或某种组合的日期?即零在一个数字日或月之前是可选的。

Is there a simple way to parse a date that may be in MM/DD/yyyy, or M/D/yyyy, or some combination? i.e. the zero is optional before a single digit day or month.

要手动完成,可以使用:

To do it manually, one could use:

String[] dateFields = dateString.split("/");
int month = Integer.parseInt(dateFields[0]);
int day = Integer.parseInt(dateFields[1]);
int year = Integer.parseInt(dateFields[2]);

并验证:

dateString.matches("\\d\\d?/\\d\\d?/\\d\\d\\d\\d")

是否会调用SimpleDateFormat或JodaTime来处理这个问题?

Is there a call to SimpleDateFormat or JodaTime that would handle this?

推荐答案

当我应该使用MM / dd / yyyy时,看起来我的问题是使用MM / DD / yyyy 。大写 D 是一年中的一天,而小写 d 是每月的日期。

Looks like my problem was using "MM/DD/yyyy" when I should have used "MM/dd/yyyy". Uppercase D is "Day in year", while lowercase d is "Day in month".

new SimpleDateFormat("MM/dd/yyyy").parse(dateString);

这份工作。此外,M / d / y可互换使用。仔细阅读 SimpleDateFormat API Docs 显示以下内容:

Does the job. Also, "M/d/y" works interchangeably. A closer reading of the SimpleDateFormat API Docs reveals the following:

对于解析,忽略模式字母的数量,除非需要将两个相邻字段分开。

"For parsing, the number of pattern letters is ignored unless it's needed to separate two adjacent fields."

这篇关于接受05/05/1999和5/5/1999等的日期时间解析的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆