阅读日历java并再次打印

时间:2015-01-05 09:27:28

标签: java string date calendar format

我知道这是一个重复的问题,但我无法理解为什么这段代码会把这个结果归还给我。也许其中一个人可以快速解决。

问题是:如何将字符串添加到日历中,之后再次显示它以检查它是否有效。输入字符串是

String time = "2015-01-05T09:20:07.532595Z";

转换它并打印它的代码是:

String pattern = "yyyy-MM-dd'T'HH:mm:ss.SSSSSS'Z'";
DateFormat df = new SimpleDateFormat(pattern, Locale.GERMANY);
Calendar cal  = Calendar.getInstance();
cal.setTime(df.parse(time));

String splitted1 = time.split("T")[1];
String[] timeSplitted = splitted1.replace("Z", "").split(":");
Integer hour = Integer.parseInt(timeSplitted[0]);
Integer minutes = Integer.parseInt(timeSplitted[1]);
String s = String.valueOf(timeSplitted[2]);
String[] timeSplitted2 = s.split("\\.");
Integer seconds = Integer.parseInt(timeSplitted2[0]);
Integer ms = Integer.parseInt(timeSplitted2[1]);

cal.set(Calendar.HOUR_OF_DAY, hour);
cal.set(Calendar.MINUTE, minutes);
cal.set(Calendar.SECOND, seconds);
cal.set(Calendar.MILLISECOND, ms);

System.out.println("[ORIGINAL]" + time);
System.out.println("[Result1    ]" + df.format(cal.getTime()));
System.out.println("[Result2    ]" + hour + ":" + minutes + ":" + seconds + "." + ms);

SimpleDateFormat format1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSSSSS");
String formatted = format1.format(cal.getTime());
System.out.println(formatted);
System.out.println(format1.parse(formatted));

结果是:

[ORIGINAL]2015-01-05T09:20:07.532595Z
[Result1    ]2015-01-05T09:28:59.000595Z
[Result2    ]9:20:7.532595
2015-01-05 09:28:59.000595
Mon Jan 05 09:28:59 CET 2015

我会答应你的所有答案。我不知道问题是在我显示结果时,还是问题出现在Calendar实例本身。我想确保变量cal被很好地解析。 提前谢谢

2 个答案:

答案 0 :(得分:1)

对于时间字符串,您应该删除纳秒。并相应地修改模式。

    String time = "2015-01-05T09:20:07.532595Z";
    String pattern = "yyyy-MM-dd'T'HH:mm:ss.SSS";
    DateFormat df = new SimpleDateFormat(pattern, Locale.GERMANY);
    Calendar cal = Calendar.getInstance();
    Date date = df.parse(time.substring(0, 23)); // remove the nanoseconds
    cal.setTime(date);

    System.out.println("[ORIGINAL   ] " + time);
    System.out.println("[Result1    ] " + df.format(cal.getTime()));

    SimpleDateFormat format1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS", Locale.GERMANY);
    String formatted = format1.format(cal.getTime());
    System.out.println("[formatted  ] " + formatted);
    System.out.println("[parsed     ] " + format1.parse(formatted));

答案 1 :(得分:0)

问题在于

cal.set(Calendar.MILLISECOND, ms)

ms的值是532595,转换为分钟时约为8分52秒,这是您在Result1和Result 2中看到的差异。

尝试将其更正为: cal.set(Calendar.MILLISECOND, ms/1000)

工作正常。

相关问题