我需要解析嵌入在某些任意文本中的日期,如下所示
"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 方法应该能够从字符串构造日期对象。
编辑
知道日期始终位于字符串的末尾,并且日期部分始终为 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/