請告訴我如何解析這個日期:「29月 - 2012」如何解析這個日期在java中
我嘗試:
new SimpleDateFormat("dd-MMM-yyyy");
但它沒有工作。我得到以下異常:
java.text.ParseException: Unparseable date: "29-July-2012"
請告訴我如何解析這個日期:「29月 - 2012」如何解析這個日期在java中
我嘗試:
new SimpleDateFormat("dd-MMM-yyyy");
但它沒有工作。我得到以下異常:
java.text.ParseException: Unparseable date: "29-July-2012"
您需要一提的語言環境,以及...
Date date = new SimpleDateFormat("dd-MMMM-yyyy", Locale.ENGLISH).parse(string);
試試這個(爲本月新增Locale.ENGLISH參數和長格式)
package net.orique.stackoverflow.question11815659;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Locale;
public class Question11815659 {
public static void main(String[] args) {
try {
SimpleDateFormat sdf = new SimpleDateFormat("dd-MMMM-yyyy",
Locale.ENGLISH);
System.out.println(sdf.parse("29-July-2012"));
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
創建的StringTokenizer。您首先需要導入庫:
import Java.util.StringTokenizer;
基本上,您需要創建一個分隔符,它基本上是用來分隔文本的東西。在這種情況下,分隔符是「 - 」(破折號)。
注意:由於您用引號顯示文本並說解析,我假設它是一個字符串。
例子:
//Create string
String input = "29-July-2012";
//Create string tokenizer with specified delimeter
StringTokenizer st = new StringTokenizer(input, "-");
//Pull data in order from string using the tokenizer
String day = st.nextToken();
String month = st.nextToken();
String year = st.nextToken();
//Convert to int
int d = Integer.parseInt(day);
int m = Integer.parseInt(month);
int y = Integer.parseInt(year);
//Continue program execution
在你的字符串,全格式用於一個月,所以根據http://docs.oracle.com/javase/6/docs/api/java/text/SimpleDateFormat.html在巴茲的意見建議,你應該使用MMMM。
原因可以從API文檔中讀取。 http://docs.oracle.com/javase/6/docs/api/java/text/SimpleDateFormat.html#month指出,如果超過3個字符,它將被解釋爲文本,並且 http://docs.oracle.com/javase/6/docs/api/java/text/SimpleDateFormat.html#text指出完整形式(在您的情況'7月'而不是'7月')將用於4個或更多字符。
使用split()
功能與分隔符"-"
String s = "29-July-2012";
String[] arr = s.split("-");
int day = Integer.parseInt(arr[0]);
String month = arr[1];
int year = Integer.parseInt(arr[2]);
// Now do whatever u want with the day, month an year values....
嘗試'DD-MMMM-yyyy'。請參閱類似的格式鏈接:http://stackoverflow.com/a/4216767/1449199 – Baz 2012-08-05 10:26:24