0

我有一个存储为字符串的值列表,我12012需要将它们相应地转换为 2012 年 1 月、2013 年 11 月、2005 年 5 月。我知道如何使用解析字符串和使用语句来做到这一点。有什么有效的方法吗?11201352005if

4

3 回答 3

4

像这样的东西可能会起作用:

String val = "12012";
int numVal = Integer.parseInt(val);
int year = numVal % 10000;
int month = numVal / 10000;
... create a date from that ...

我不知道你是否想要一个javaDateCalendar其他什么。

Calendar cal = Calendar.getInstance().clear();
cal.set(year, month-1, 1);

Date date = cal.getTime();

或 Joda Time 用于没有时区的日期:

LocalDate dt = new LocalDate(year, month, 1);
于 2013-10-10T17:18:33.177 回答
3

使用 SimpleDateFormat 模式,您可以轻松做到这一点:尝试以下简单代码:

String str="12012";//112013 , 52005
SimpleDateFormat format=new SimpleDateFormat("Myyyy");
SimpleDateFormat resFormat=new SimpleDateFormat("MMM yyyy");
Date date=format.parse(str);
System.out.println(resFormat.format(date));
于 2013-10-10T17:22:38.077 回答
3

由于您有代表具有两种不同格式 Myyyy 和 MMyyyy 的日期的字符串,因此SimpleDateFormat我不确定您是否可以避免使用 if 语句,这就是我的做法:

    SimpleDateFormat sdf1 = new SimpleDateFormat("Myyyy");
    SimpleDateFormat sdf2 = new SimpleDateFormat("MMyyyy");
    Date d = null;
    if(5 == s.length()){
        d = sdf1.parse(s);
    }else if(6 == s.length()){
        d = sdf2.parse(s);
    }
于 2013-10-10T17:37:27.030 回答