Clever way to separate year, month and day from date string?

I have date string, which is in the following format: 2014-Mar-30. I want to separate it into 3 strings: 2014, Mar, 30. Any clever way to do so? (java)

Answers


Try this method:

String[] arr = strDate.split("-");
String strYear = arr[0];
String strMonth = arr[1];
String strDay = arr[2];

The quick and dirty way, for your exact case, is to use String.split('-'). (as in @Vyger)

However, a more robust way might be to use regular expressions and search for 4 digits in a row, 3 letters in a row, and whatever is left over (1 or 2 digits). That way you might be able to handle a lot of plausible alternates like

"Mar-30-2014" or even "Mar 30 2014"


I tend to use something like this.

String totalString = "2014-Mar-30";
String yearString = totalString.substring(0, totalString.indexOf('-'));
String monthString = totalString.substring(totalString.indexOf('-') + 1, totalString.lastIndexOf('-'));
String dayString = totalString.substring(totalString.lastIndexOf('-') + 1);

Hope this helps :)


Need Your Help

Filtering a c# collection by multiple parameters where some may be null

c# linq linq-to-objects

I'm sorry if this is a duplicate question, I have found some similar ones, but not one that would solve my problem. I have a collection of objects with various parameters and I want to filter them ...

Arquillian + shrinkwrap-resolver: Unable to boostrap Aether repository system

java maven aether shrinkwrap jboss-arquillian

We have integration tests which are made with Arquillian. Shrinkwrap is used to resolve maven dependencies and build EAR file for tests. I just upgraded dependency of org.jboss.shrinkwrap.resolver: