Java

时间:2015-05-29 09:36:44

标签: java

我在Strings中有两种日期格式,即:

1981年12月7日 和 1991年7月11日

String one_date = "1981-12-07";
String another_date = "07-11-1991";

我需要以一种格式转换它们。

例如在" yyyy-MM-dd&#34 ;;

我想要的只是将这些字符串正确插入到sqlite数据库中,所以它们应该是相同的格式,好吗?

java SimpleDataFormat在没有检查的情况下吃掉所有东西。

子串不适用于此处。 有人可以告诉我检查的方法吗?

4 个答案:

答案 0 :(得分:1)

您需要编写一个代码,以便在解析之前区分日期版本。您需要根据要解析的字符串的某些特征自行编写此代码。对于那两个,我会做

if (one_date.split("-")[2].length()==2) {
    // parse it with yyyy-MM-dd
} else {
 // parse it with dd-MM-yyyy or something
}

你也可以使用.lastIndexOf(' - ');检查最后一个' - '是的,性能会更好

当然我们可以使用.charAt(somePositionIndex)检查' - '标志是我们期望找到的地方。

答案 1 :(得分:0)

您可以这样做:

    SimpleDateFormat defaultFormat = new SimpleDateFormat("yyyy-MM-dd");
    SimpleDateFormat secondFormat = new SimpleDateFormat("dd-MM-yyyy");
    String one_date = "1981-12-07";
    String another_date = "07-11-1991";
    String[] strs = new String[] { one_date, another_date };
    ArrayList<Date> dates = new ArrayList<Date>();
    for (String s : strs) {
        try {
            if (s.matches("\\d{4}-\\d{2}-\\d{2}")) {
                dates.add(defaultFormat.parse(s));
            } else {
                dates.add(secondFormat.parse(s));
            }
        } catch (ParseException e) {
            e.printStackTrace();
        }
    }
    ArrayList<String> converted = new ArrayList<String>();
    for (Date d : dates) {
        converted.add(defaultFormat.format(d));
    }
    System.out.println(converted);

答案 2 :(得分:0)

我有许多不同的日期格式,建议您使用natty

以下是如何使用它来返回日期的示例。一旦你有这个日期,你可以简单地格式化它,无论如何。

import com.joestelmach.natty.DateGroup;
import com.joestelmach.natty.Parser;
import java.util.Date;

public class ParseDate {
   public static Date parse(String date)throws Exception{
        Parser parser = new Parser();
        List<DateGroup> groups =  parser.parse(date);


        int year;
        int day=1;
        int month=1;
        for(DateGroup group : groups){
            for( Date d : group.getDates()){
                year=d.getYear();
                month=d.getMonth();
                day=d.getDay();
                Date fixedDate=new Date(year,month,day);
                return fixedDate;
            }
        }

        throw new Exception("unparsable date");
 }
}

答案 3 :(得分:0)

其他答案过于复杂。

用于解析异常的陷阱

使用一种格式进行简单的尝试解析,捕获由不匹配的输入引起的异常。如果抛出异常,请尝试其他格式。

另外,请避免使用java.util.Date/.Calendar类。它们出了名的麻烦,现在被java.time包和/或Joda-Time库所取代。

相关问题