简体   繁体   中英

Java: How to extract date from the string

I am building groovy test and have the String in Properties:

date = new Date("09/15/2016")

Need to extract the String part with date like:

y=09/15/2016

I tried with substring method and it works but what if I want to use other methods like Regular expression or DateFormat?

This will work:

        Date date = new Date("09/15/2016");
        String strDate = new SimpleDateFormat("MM/dd/yy").format(date);
        System.out.println(strDate);

As you've tagged this groovy, you can also do:

Date date = Date.parse("MM/dd/yyyy", "09/15/2016")

Update:

Ok...Weird... I didn't understand you actually had new Date(blah) as a String

This should work then, guess you do need a regexp ;-)

String weirdDateString = 'new Date("09/15/2016")'

String extractedDate = weirdDateString.find(/[0-9\/]+/)

Date date = Date.parse('MM/dd/yyyy', extractedDate)

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