How to extract a date from a string and put it into a date variable in Java

前端 未结 5 1536
日久生厌
日久生厌 2020-12-19 20:39

I have been looking around stack-overflow and various other websites for the solution to my problem but haven\'t found any suitable for my specific purposes and have been un

5条回答
  •  自闭症患者
    2020-12-19 21:25

    The following are the implemented program to search for the string and parse it to the date object.

    import java.text.ParseException;
    import java.text.SimpleDateFormat;
    import java.util.regex.Matcher;
    import java.util.regex.Pattern;
    
    public class StringInBetween {
        public static void main(String[] args) throws ParseException {
            //"name+" at:"+Date+" Notes:"+meetingnotes" (name, Date and meetingnotes being variables).
            String test = "rama"+ " at:"+"2015-01-02"+" Notes:"+"meetingnotes";
    
            Pattern pattern = Pattern.compile("at:(.*)Notes");
            Matcher matcher = pattern.matcher(test);
    
            if(matcher.find())
            {
                String dateString = matcher.group(1);   //I'm using the Capturing groups to capture only the value.
                java.util.Date date = new SimpleDateFormat("yyyy-mm-dd").parse(dateString);
                System.out.println(date);
            }
        }
    }
    

提交回复
热议问题