Parse specific date string format

一笑奈何 提交于 2019-12-11 07:04:59

问题


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:


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


来源:https://stackoverflow.com/questions/16598650/parse-specific-date-string-format

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!