3

I have a String instance as following format:

yyyyMMddHHmmss

and I want split any element of it to a integer variable. for sample:

String date_time = "20080519145436"; 

By above string result must be:

int year  = 2008;
int month  = 05;
int day  = 19;
int hour  = 14;
int minutes  = 54;
int second  = 36;

I found two way for solve this issue:

  1. using a SimpleDateFormatter and fetch elements.
  2. using subString() method of String class.

My question is: Which way is proposed? There are another ways?

4

5 回答 5

7

使用JodaTime中的日期格式化机制。

例如:

final DateTimeFormatter parser = DateTimeFormat.forPattern ( "yyyyMMddHHmmss" );
final DateTime date = parser.parseDateTime( "20080519145436" );
int year = date.getYear();
...
于 2012-12-30T08:14:49.577 回答
2

你可以简单地使用 SimpleDateFormat

String date_time = "20080519145436"; 
        SimpleDateFormat df =new SimpleDateFormat("yyyyMMddHHmmss");
        Date d= df.parse(date_time);
        Calendar cal = Calendar.getInstance();
        cal.setTime(d);
        System.out.println(cal.get(Calendar.YEAR));
于 2012-12-30T08:21:34.080 回答
2

甚至不要考虑使用 String.subString()。日期不是字符串,您不应该尝试将其作为字符串处理,因为您绝对不会对输入进行完整性检查。您可以输入任何 14 位输入,您的算法会将其拆分为无意义的日期部分,例如月 = 42。在这种情况下,使用 SimpleDateFormatter、JodaTime 或任何其他专门针对日期对象的算法将引发异常。

于 2012-12-30T08:34:43.447 回答
0

另一种方法是

    long d = Long.parseLong("20080519145436");
    int year = (int) (d / 10000000000L);
    int month = (int) (d / 100000000L % 100);
    int day = (int) (d / 1000000L % 100);
    int hour = (int) (d / 10000L % 100);
    int minutes = (int) (d / 100L % 100);
    int second = (int) (d % 100);

至于我认为#2更快的选项

int year = Integer.parseInt(date_time.substring(0, 4)); 
...

因为已知 SimpleDateFormat 很慢。

于 2012-12-30T08:20:29.547 回答
0

使用 SimpleDateFormatter 并获取元素。

于 2012-12-30T08:40:08.360 回答