javastringdatetime

Which method is proposed for split date string?


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?


Solution

  • Use the date formatting mechanisms in JodaTime.

    For example:

    final DateTimeFormatter parser = DateTimeFormat.forPattern ( "yyyyMMddHHmmss" );
    final DateTime date = parser.parseDateTime( "20080519145436" );
    int year = date.getYear();
    ...