java 如何从字符串中提取日期并将其放入Java中的日期变量中

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/34829962/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-02 23:25:19  来源:igfitidea点击:

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

javaregexstringdate

提问by PythoniusNoobus

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+" 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?

(姓名、日期和会议记录是变量)。我想要做的是提取字符串的日期部分并将其粘贴在日期变量中。日期的基本日期格式是“yyyy-MM-dd”。我该怎么做呢?

采纳答案by Andreas

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+:

或者在 Java 8+ 中:

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

回答by vaibhav singh

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.

一种日期模式识别算法,不仅可以识别日期模式,还可以获取 Java 日期格式的可能日期。该算法非常快速且轻量级。处理时间是线性的,所有日期都在一次传递中确定。算法使用树遍历机制解析日期。树数据结构是自定义创建的,以构建受支持的日期、时间和月份模式。

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

该算法还确认日期文字之间的多个空格字符。例如,DD DD DD 和 DD DD DD 被视为有效日期。

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)

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

其中 M 是月份文字是字母格式,如 Jan 或 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

它还识别以下格式的拖尾时间模式 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

解析时间是线性的,不使用模式匹配或蛮力。该算法基于树遍历并返回,日期列表具有以下三个组成部分 - 文本中标识的日期字符串 - 转换和格式化的日期字符串 - 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.

算法库可在 Maven 中心获得。

<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}]

输出:[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,结束=46}]

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

详细博客在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

完整源代码可在 GitHub 上获取,网址https://github.com/vbhavsingh/DateParser

回答by ivan

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

代码来自这里

回答by Ramasamy Kasiviswanathan

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

回答by Basil Bourque

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:.

技术含量低但简单的方法是搜索围绕您所需文本的两个已知部分:at: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::indexOfto learn those positions. Then use String::substring`to extract the text representing your date value.

如果您确定这些文本片段从未出现在其他文本中,您可以搜索每个片段以了解它们在整个字符串中的位置。使用String::indexOf学习这些位置。然后使用String::substring`提取表示日期值的文本。

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

LocalDate

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

取出提取的文本并解析它以获得一个LocalDate对象。解析字符串以获取日期时间已被多次介绍,请搜索 StackOverflow 以了解更多信息。

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

您指定的 yyyy-MM-dd格式符合标准ISO 8601格式。java.time 类在解析/生成字符串时默认使用这些标准格式。

    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

摘录:2016-01-16

ld.toString(): 2016-01-16