Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/date/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何在Java中将数值转换为日期?_Java_Date - Fatal编程技术网

如何在Java中将数值转换为日期?

如何在Java中将数值转换为日期?,java,date,Java,Date,我有一个以字符串形式存储的值1201120135205的列表,我需要将它们相应地转换为2012年1月、2013年11月和2005年5月。我知道如何通过解析字符串和使用if语句来实现这一点。有什么有效的方法吗?类似的方法可能会奏效: String val = "12012"; int numVal = Integer.parseInt(val); int year = numVal % 10000; int month = numVal / 10000; ... create a date fro

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

类似的方法可能会奏效:

String val = "12012";
int numVal = Integer.parseInt(val);
int year = numVal % 10000;
int month = numVal / 10000;
... create a date from that ...
我不知道你是想要java日期或日历还是别的什么

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

Date date = cal.getTime();
或Joda时间,用于无时区的日期:

LocalDate dt = new LocalDate(year, month, 1);

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

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));

由于字符串表示的日期有两种不同的格式Myyyy和MMyyyy,使用SimpleDataFormat,我不确定您是否可以避免使用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);
    }

查看SimpleDataFormat.has的可能副本作为第一次点击我不确定这是否有效,因为示例Myyyy和MMyyyy中给出了两种类型的日期,如果您使用112013尝试解决方案,它将打印:2013年1月12013日而不是2013年11月