简体   繁体   English

如何将字符串转换为日期?

[英]How to convert a string to a Date?

I don't know what format string is 我不知道格式字符串是什么

May be 2015-10-10 or 2015/10/10 , may also be 2015-10-30 15:30 可能是2015-10-102015/10/10 ,也可能是2015-10-30 15:30

Regular first I want to use to judge whether a valid date or time, and then use the SimpleDateFormat parsing, what should I do better? 定期首先我想用来判断一个有效的日期或时间,然后使用SimpleDateFormat解析,我该怎么办?

All formats include: 所有格式包括:

- yyyy-MM-dd
- yyyy.MM-dd
- yyyy/MM/dd
- yyyy-MM-dd HH24:mm
- yyyy.MM-dd HH24:mm
- yyyy/MM/dd HH24:mm
- yyyy-MM-dd HH24:mm:ss
- yyyy.MM-dd HH24:mm:ss
- yyyy/MM/dd HH24:mm:ss
use following date formatter to convert the date to String.
String d="2015-05-12";
DateFormat formatter  = new SimpleDateFormat("yyyy-mm-dd");
Date a=formatter.parse(d);

I've used Natty Date Parser for this. 我已经使用了Natty Date Parser You can try it out here . 你可以在这里试试。 It is available on maven central here . 它可用于Maven的中央位置 If you are using gradle: 如果您使用的是gradle:

compile 'com.joestelmach:natty:0.12'

Example usage: 用法示例:

String[] exampleDates = {
    "2015-10-10",
    "2015/10/10",
    "2015-10-30 15:30"
};

Parser parser = new Parser();
for (String dateString : exampleDates) {
  List<DateGroup> dates = parser.parse(dateString);
  Date date = dates.get(0).getDates().get(0);
  System.out.println(date);
}

Output: 输出:

Sat Oct 10 20:51:10 PDT 2015 10月10日星期六20:51:10 PDT 2015

Sat Oct 10 20:51:10 PDT 2015 10月10日星期六20:51:10 PDT 2015

Fri Oct 30 15:30:00 PDT 2015 10月30日星期五15:30:00 PDT 2015


EDIT: 编辑:

If you know the date formats then the following StackOverflow would be better than adding a dependency to your project: 如果您知道日期格式,那么以下StackOverflow将比向项目添加依赖项更好:

https://stackoverflow.com/a/4024604/1048340 https://stackoverflow.com/a/4024604/1048340


The following static utility method might suffice: 以下静态实用程序方法可能就足够了:

/**
 * Parses a date with the given formats. If the date could not be parsed then {@code null} is
 * returned.
 *
 * @param formats the possible date formats
 * @param dateString the date string to parse
 * @return the {@link java.util.Date} or {@code null} if the string could not be parsed.
 */
public static Date getDate(String[] formats, String dateString) {
  for (String format : formats) {
    SimpleDateFormat sdf = new SimpleDateFormat(format);
    try {
      return sdf.parse(dateString);
    } catch (ParseException ignored) {
    }
  }
  return null;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM