简体   繁体   中英

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)

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 :)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM