Java 如何将两种不同类型的字符串格式解析为一个日期?
我正在尝试这样的日期格式 2011年8月和2011年8月24日 我现在用这个来解析它们Java 如何将两种不同类型的字符串格式解析为一个日期?,java,android,simpledateformat,Java,Android,Simpledateformat,我正在尝试这样的日期格式 2011年8月和2011年8月24日 我现在用这个来解析它们 //set the pattern here to look like the pattern you are expecting in your 'Date' variable SimpleDateFormat sdf = new SimpleDateFormat("MMMM dd,yyyy"); //Get the release date
//set the pattern here to look like the pattern you are expecting in your 'Date' variable
SimpleDateFormat sdf = new SimpleDateFormat("MMMM dd,yyyy");
//Get the release date
releaseDate = postIt.next().text();
Date realDate = null;
try {
realDate = sdf.parse(releaseDate);
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
int i = 0;
String gameDate = realDate.toString();
我在调试中遇到以下错误
08-26 22:02:44.571: WARN/System.err(29218): java.text.ParseException: Unparseable date: "August 2011" (at offset 11)
08-26 22:02:44.571: WARN/System.err(29218): at java.text.DateFormat.parse(DateFormat.java:626)
我将如何使这两种格式都可以读取
编辑:
这就是它现在解析它的方式
08-27 00:10:48.951: VERBOSE/Dates(30449): August 2011
如果在2011年8月形成
到
它们都解析到同一个日期。我想每个都需要一个格式字符串,例如
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
public class DateFormatDriver {
public static void main( String[] args ) throws Exception {
SimpleDateFormat dayMonthYearFormatter = new SimpleDateFormat("MMMM dd,yyyy");
SimpleDateFormat monthYearFormatter = new SimpleDateFormat("MMMM yyyy");
//String date1 = "August 11,2005";
String date1 = "August 2005";
Date realDate = null;
try {
realDate = dayMonthYearFormatter.parse(date1);
System.out.println("parsed date -> " + realDate);
} catch (ParseException e) {
// fall back on other formatter
try {
realDate = monthYearFormatter.parse(date1);
System.out.println("parsed date -> " + realDate);
} catch(ParseException e2) {
System.err.println("could not parse" + date1);
}
}
}
}
我建议你退房
这只是一个想法,不确定我是否真的会使用它,但可以使用标记器查看它是什么日期类型,2个标记表示“2005年8月11日”,1个标记表示“2005年8月”。因此,如果令牌计数为1,则使用一个格式化程序;如果令牌计数为2,则使用另一个格式化程序
int tokenCount = 0;
StringTokenizer tokenizer = new StringTokenizer("August 11, 2005", ",");
while(tokenizer.hasMoreTokens()) {
tokenizer.nextToken();
tokenCount++;
}
System.out.println("token count -> " + tokenCount);
我怎么知道是2011年8月21日,还是仅仅2011年8月?根据一个列表?还有你在Joda Time中的建议是什么?取决于,你从哪里获得来自“2011年8月21日”和“2011年8月”的字符串?引用这篇文章——“一个易于使用的Java开源日期/时间库”,它应该可以节省你解析日期的时间™ 正如您将在本文中看到的,Joda Time减轻了操作日期和时间的痛苦和繁琐。“我从HTML页面获取它们,然后返回到每个日期的列表中。。。如果日期为2011年8月21日格式,则会进行解析。如果是2011年8月,那就不是了。
int tokenCount = 0;
StringTokenizer tokenizer = new StringTokenizer("August 11, 2005", ",");
while(tokenizer.hasMoreTokens()) {
tokenizer.nextToken();
tokenCount++;
}
System.out.println("token count -> " + tokenCount);