简体   繁体   中英

Parse specific date string format

I have read a lot of questions and searched for a lot of libs all over the internet but I can't find one that can do this quickly.

I want to parse a specific date in a specific date format like this:

String date = "20130516T090000";
SimpleDateFormat x = new SimpleDateFormat("yyyyMMddTHHmmss");

String theMonth = x.parse(date, "M"); // 05
String theMonth = x.parse(date, "MMM"); // MAY
String theMinute = x.parse(date, "mm"); // 00
String theYear = x.parse(date, "yyyy"); // 2013

Just simple as that. A way to set a Parse Rule, a Specific Date Format and a way to retrieve each data i want (Month, Minute, Year....)

Is there a good library to do EXACTLY this? If yes could you put an example together? If no, is there a good way to do this without much code?

Thanks in advance!

  1. Use the SimpleDateFormat class to parse a date from a String to a Date instance.

     String date = "20130516T090000"; SimpleDateFormat x = new SimpleDateFormat("yyyyMMdd'T'HHmmss"); Date d = x.parse(date); 

    There was a problem in your SimpleDateFormat format String, text in the format has to be quoted using single quoted (') to avoid interpretation.

  2. Use the Calendar class to get the part of the date you want.

     Calendar cal = Calendar.getInstance(); cal.setTime(d); String theYear = String.valueOf(cal.get(Calendar.YEAR)); String theMonth = String.valueOf(cal.get(Calendar.MONTH)); String theMinute = String.valueOf(cal.get(Calendar.MINUTE)); 

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