关于java:如何在android中将String转换为Date

how to convert String to Date in android

本问题已经有最佳答案,请猛点这里访问。

我有字符串日期时间"2014-10-13 18:22:54.71",我想把它转换成Date

我用那个算法

1
2
3
4
5
6
7
8
public static boolean IsthatMorethanTwo(String DateString) {
    Calendar thatDay = Calendar.getInstance();
    thatDay.setTime(new Date(DateString));
    Calendar today = Calendar.getInstance();
    long diff = today.getTimeInMillis() - thatDay.getTimeInMillis();
    long days = diff / (24 * 60 * 60 * 1000);
    return days >= 2;
}

我该怎么做?


您可以使用SimpleDateFormat类。

这样地:

1
2
3
4
5
6
7
8
9
10
String dateString ="2014-10-13 18:22:54.71";    
SimpleDateFormat format =
        new SimpleDateFormat("yyyy-mm-dd HH:mm:ss.S");

try {
    Date parsed = format.parse(dateString);
}
catch(ParseException pe) {
    System.out.println("ERROR: Cannot parse "" + dateString +""");
}