3

请告诉我如何解析这个日期:“2012 年 7 月 29 日”

我尝试:

new SimpleDateFormat("dd-MMM-yyyy");

但它不起作用。我得到以下异常:

java.text.ParseException: Unparseable date: "29-July-2012"
4

5 回答 5

5

您还需要提及语言环境...

Date date = new SimpleDateFormat("dd-MMMM-yyyy", Locale.ENGLISH).parse(string);
于 2012-08-05T10:47:18.733 回答
3

在您的字符串中,完整格式用于月份,因此根据http://docs.oracle.com/javase/6/docs/api/java/text/SimpleDateFormat.html您应该按照 Baz 评论中的建议使用 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声明完整形式(在您的情况下为“July”而不是“Jul”)将用于 4 个或更多字符。

于 2012-08-05T10:34:38.997 回答
2

试试这个(添加 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();
        }

    }

}
于 2012-08-05T10:33:29.620 回答
1

使用带分隔符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....
于 2012-08-05T10:57:23.890 回答
0

创建一个 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
于 2012-08-05T10:34:14.870 回答