java - 解析Java中其他文本中嵌入的日期

标签 java date

我需要解析嵌入在某些任意文本中的日期,如下所示

"hello world, good Day Thu Mar 03 07:13:56 GMT 2011"

I know the pattern of the date (below), however I'm not sure how to parse it from the text string above. How do I do it?

String format = "E MMM dd HH:mm:ss z yyyy";
new SimpleDateFormat(format).parse(date);

最佳答案

您可以使用 DateFormat 类!

假设您知道日期在文本中的索引,

String text = "hello world, good Day Thu Mar 03 07:13:56 GMT 2011";
String dateText = text.substring(22);
DateFormat df = DateFormat.getDateInstance();
Date date = df.parse(dateText);

如果格式正确,parse 方法应该能够从字符串构造日期对象。

这是documentation

编辑

知道日期始终位于字符串的末尾,并且日期部分始终为 28 个字符长(?)...您可以剪掉字符串的末尾并将其解析为日期。

String text = "hello world, good Day Thu Mar 03 07:13:56 GMT 2011";
String dateText = text.substring(text.length()-28); //28 is the date portion
DateFormat df = DateFormat.getDateInstance();
Date date = df.parse(dateText);

关于java - 解析Java中其他文本中嵌入的日期,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6409215/

相关文章:

java - 当数据不以新行结尾时,有没有办法从套接字中读取数据?

javascript - 将时间格式转换为iso格式

php - php 中的年和周至今

java - 日期格式不会解析字符串

java - 如何将日期从英语转换为阿拉伯语

java - 在 JSP 中上传和保存文件

java - 如何使 compareTo 方法尊重一般契约(Contract)?

sharepoint - Powershell 日期到 Sharepoint 日期

java - 软件中的“独立交易”是什么?

java - 如何调用字符串数组中的 Java 方法? (java.lang.NoSuchMethodException)