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

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

本文介绍了如何从字符串中提取日期并将其放入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 +注释: + meetingnotes

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

(名称,日期和会议注释是变量)。我想做的是提取字符串的日期部分并将其粘贴在Date变量中。日期的基本Dateformat是 yyyy-MM-dd。我该怎么做?

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

或在Java 8+中:

Or in Java 8+:

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

这篇关于如何从字符串中提取日期并将其放入Java中的日期变量中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-07 04:02