【问题标题】:Read calendar java and print it again阅读日历java并再次打印
【发布时间】:2015-03-02 19:35:56
【问题描述】:

我知道这是一个重复的问题,但我不明白为什么这段代码会返回这个结果。也许你们中的一个人可以很快解决它。

问题是:如何获取一个字符串到日历,然后再次显示它以检查它是否有效。输入字符串是

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

我会感谢您的所有回答。我不知道问题是在我显示结果时还是在日历实例本身中。我想确保变量 cal 被很好地解析。 提前谢谢你

【问题讨论】:

    标签: java string date calendar format


    【解决方案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));
    

    【讨论】:

      【解决方案2】:

      问题出在

      cal.set(Calendar.MILLISECOND, ms)
      

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

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

      效果很好。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2013-10-31
        • 2019-11-06
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-06-05
        • 2021-07-13
        相关资源
        最近更新 更多