简体   繁体   中英

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

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 unable to change these solutions to suit my code. These include regex codes which I do not fully understand or know how to manipulate.

So here is my question, I have a string which has a structure:

"name+" at:"+Date+" Notes:"+meetingnotes"

(name, Date and meetingnotes being variables). What I want to do is extract the date part of the string and stick it in a Date variable. The basic Dateformat for the dates is "yyyy-MM-dd". How do I do this?

For this, a regular expression is your friend:

String input = "John Doe at:2016-01-16 Notes:This is a test";

String regex = " at:(\\d{4}-\\d{2}-\\d{2}) Notes:";
Matcher m = Pattern.compile(regex).matcher(input);
if (m.find()) {
    Date date = new SimpleDateFormat("yyyy-MM-dd").parse(m.group(1));
    // Use date here
} else {
    // Bad input
}

Or in Java 8+:

    LocalDate date = LocalDate.parse(m.group(1));

A date pattern recognition algorithm to not only identify date pattern but also fetches probable date in Java date format. This algorithm is very fast and lightweight. The processing time is linear and all dates are identified in a single pass. Algorithm resolves date using tree traverse mechanism. Tree data structures are custom created to build supported date, time and month patterns.

The algorithm also acknowledges multiple space characters in between Date literals. Eg DD DD DD and DD DD DD are considered as valid dates.

Following date-patterns are considered as valid and are identifiable using this algorithm.

dd MM(MM) yy(yy) yy(yy) MM(MM) dd MM(MM) dd yy(yy)

Where M is month literal is alphabet format like Jan or January

Allowed delimiters between dates are '/', '\\', ' ', ',', '|', '-', ' '

It also recognizes trailing time pattern in following format hh(24):mm:ss.SSS am / pm hh(24):mm:ss am / pm hh(24):mm:ss am / pm

Resolution time is linear, no pattern matching or brute force is used. This algorithm is based on tree traversal and returns back, the list of date with following three components - date string identified in the text - converted & formatted date string - SimpleDateFormat

Using date string and the format string, users are free to convert the string into objects based on their requirements.

The algorithm library is available at maven central.

<dependency>
    <groupId>net.rationalminds</groupId>
    <artifactId>DateParser</artifactId>
    <version>0.3.0</version>
</dependency>

The sample code to use this is below.

 import java.util.List;  
 import net.rationalminds.LocalDateModel;  
 import net.rationalminds.Parser;  
 public class Test {  
   public static void main(String[] args) throws Exception {  
        Parser parser=new Parser();  
        List<LocalDateModel> dates=parser.parse("Identified date :'2015-January-10 18:00:01.704', converted");  
        System.out.println(dates);  
   }  
 }

Output: [LocalDateModel{originalText=2015-january-10 18:00:01.704, dateTimeString=2015-1-10 18:00:01.704, conDateFormat=yyyy-MM-dd HH:mm:ss.SSS, start=18, end=46}]

Detailed blog at http://coffeefromme.blogspot.com/2015/10/how-to-extract-date-object-from-given.html

The complete source is available on GitHub at https://github.com/vbhavsingh/DateParser

You could use parse like this:

String fromDate = "2009/05/19";
DateFormat df = new SimpleDateFormat("yyyy/MM/dd");
java.util.Date dtt = df.parse(fromDate);

this turns any(well formatted) string into a date variable.

the code is from here

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

Regex is overkill

Regex may be overkill for this, especially for a beginning programmer.

The low-tech but simple way is to search for the two known pieces that surround your desired text: at: and Notes: .

Provided you are certain those pieces of text never occur in the other text, you can search for each piece to learn their position in the overall string. Use String::indexOf to learn those positions. Then use String::substring` to extract the text representing your date value.

String input = "John Doe at:2016-01-16 Notes:This is a test";

String at = "at:";  // We expect these two pieces of text to be embedded.
String notes = " Notes:";

// Verify that our expected pieces of text are indeed embedded.
if ( ! ( input.contains ( at ) && input.contains ( notes ) ) ) {
    // …handle error…
    System.out.println ( "ERROR - unexpected input" );
    return;
}

int indexAt = input.indexOf ( at );
int indexNotes = input.indexOf ( notes );
String extracted = input.substring ( indexAt + at.length ( ), indexNotes );

LocalDate

Take that extracted text and parse it to obtain a LocalDate object. Parsing a String to get a date-time has been covered many many times do please search StackOverflow to learn more.

Your specified format of yyyy-MM-dd complies with standard ISO 8601 formats. The java.time classes use these standard formats by default when parsing/generating strings.

    LocalDate localDate = LocalDate.parse ( extracted );

    System.out.println ( "extracted: " + extracted );
    System.out.println ( "localDate.toString(): " + localDate );

extracted: 2016-01-16

ld.toString(): 2016-01-16

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