开发者

Java regex to extract date format out into month and year

Hi I have the following date string format:

June-2008

July-2008

March-2010

May I enquire what is the java regex to extract out whatever the month and year value into separate string each. The delimeter here is the "-" sign

Any values from开发者_如何学C the start to the end of the "-" sign is the month, anything after the "-" sign is the year value.

The following is what I would like to achieve

String m = March   
String y = 2010

Thank all for your help!


Don't use a regex. Use String#split():

String[] parts = "June-2008".split("-", 2); // or .split("-")
String m = parts[0]; // "June"
String y = parts[1]; // "2008"

Even better, use SimpleDateFormat, and you'll have a proper Date to work with:

DateFormat df = new SimpleDateFormat("M-y");
Date myDate = df.parse("June-2008");


I want to extend the answer given by Matt Ball. If you want to split that string and willing to use other than String#split() you can use StringUtils of Apache Commons Lang. It has various String utility methods.

An example:

String strDate = "June-2008";
String[] parts = StringUtils.split(strDate, '-');
String month = parts[0]; // "June"
String year = parts[1]; // 2008

Also if you want to get a java.util.Date object then Joda Time may helps you. I personally prefer this api rather java.util.Date as it is far more rich, easy-to-use, less error-pron.

Now we can manipulate that String as:

String strDate = "June-2008";
DateTimeFormatter formatter = DateTimeFormat.forPattern("MMMM-yyyy");
DateTime dateTime = formatter.parseDateTime(strDate); // parse it
Date javaDate = dateTime.toDate(); // a java.util.Date object
int year = dateTime.getYear(); // 2008
String month = dateTime.month().getAsText(); // June

Hope this will help you. Thanks.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜