的具體格式我有這些字符串如何解析日期字符串
String day1 = "June 3, 2015";
和
String day2 = "June 25, 2015";
我想創建一個方法來解析出的月,日和年。目前我正在使用substring(),但認爲可能有更好的解決方案?
的具體格式我有這些字符串如何解析日期字符串
String day1 = "June 3, 2015";
和
String day2 = "June 25, 2015";
我想創建一個方法來解析出的月,日和年。目前我正在使用substring(),但認爲可能有更好的解決方案?
解決方案1:
使用的StringTokenizer來標記串例如:從日期
String str = "June 3, 2015";
StringTokenizer defaultTokenizer = new StringTokenizer(str);
while (defaultTokenizer.hasMoreTokens())
{
System.out.println(defaultTokenizer.nextToken());
}
刪除 '' 即使用deletecharAt(INT指數)第二令牌;
希望爲你
方案2的工作原理: 使用split()方法
for (String retval: Str.split(" ", 3)){
System.out.println(retval);
}
split() takes two argument first it will take the token , and the limit is how many strings. still you have to remove ',' .
還有一個最簡單的辦法: 解決方案3:
SimpleDateFormat format = new SimpleDateFormat("MMMM d, yyyy");
Date date1 = format.parse(day1);
Date date2 = format.parse(day2);
[JavaDoc](http://docs.oracle.com) com/javase/7/docs/api/java/util/StringTokenizer.html)說:*'StringTokenizer'是一個遺留類,爲了兼容性的原因被保留,儘管它在新代碼中的使用不受歡迎。建議任何尋求這種功能的人都使用'String'或'java.util.regex'包中的'split'方法。* – RealSkeptic
注意這相當於到MMMM dd, yyyy
試試這個。
SimpleDateFormat sdf = SimpleDateFormat("MMMM dd, yyyy");
Date parsed = sdf.parse(day1, new ParsePosition(0));
...
ps:我沒有試過這個代碼,請隨時評論任何東西。
使用SimpleDateFormat,並從那裏解析日期。
SimpleDateFormat format = new SimpleDateFormat("MMMM d, yyyy");
Date date1 = format.parse(day1);
Date date2 = format.parse(day2);
ROLF,這與我剛纔的方法相同:D –
你可以嘗試像
private static final String DAY = "dd";
private static final String MONTH = "MM";
private static final String YEAR = "yyyy";//use the format you want this just an example
Format month = new SimpleDateFormat(MONTH);
Format day = new SimpleDateFormat(DAY);
Format year = new SimpleDateFormat(YEAR);
month.format(your date);
day.format(your date);
year.format(your date);
'SimpleDateFormat'吧? –
http://stackoverflow.com/questions/16208121/java-create-date-object-using-a-value-string –
可能的重複[如何解析/格式與LocalDateTime日期? (Java 8)](http://stackoverflow.com/questions/22463062/how-to-parse-format-dates-with-localdatetime-java-8) – RealSkeptic