使用SimpleDateFormat.parse()时获取错误的数据 [英] Getting wrong data when using SimpleDateFormat.parse()

查看:126
本文介绍了使用SimpleDateFormat.parse()时获取错误的数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我尝试将字符串解析为日历时,我遇到了最奇怪的错误。
似乎它弄乱了Date对象,我用它设置结果日历的时间。错误是非常不一致的(或者我看不到逻辑)。任何人都可以指出我可能做错了什么?

I am getting the strangest error, when trying to parse a string as a calendar. It seems that it messes up the Date object which I use to set the result calendar's time. The error is pretty inconsistent (or I see no logic in it). Can anyone point out what I might be doing wrong ?

public class caltest{
public static final SimpleDateFormat sdf = new SimpleDateFormat("YYYY-MM-dd HH:mm:ss.SSS");

public static void main(String[] args) {
    String date1 = "1992-03-11 12:00:12.123";
    String date2 = "1993-03-11 12:00:12.123";
    String date3 = "1994-03-11 12:00:12.123";
    String date4 = "1995-03-11 12:00:12.123";
    parseStringAsCalendar(date1);
    parseStringAsCalendar(date2);
    parseStringAsCalendar(date3);
    parseStringAsCalendar(date4);
}
public static String calendarToString(Calendar cal) {
    return sdf.format(cal.getTime());
}

public static Calendar parseStringAsCalendar(String s) {
    Date time = null;
    try {
        time = sdf.parse(s);
    } catch (ParseException e) {
        System.out.println("Exception");
        e.printStackTrace();
    }
    System.out.println(time.toString());
    GregorianCalendar ret = new GregorianCalendar();
    ret.setTime(time);

    return ret;
}

}

输出是:

Sun Dec 29 12:00:12 CET 1991
Sun Dec 27 12:00:12 CET 1992
Sun Dec 26 12:00:12 CET 1993
Sun Jan 01 12:00:12 CET 1995


推荐答案

您在格式说明符中使用 YYYY ,这是 week year (从Java 7开始,我相信)。你想要 yyyy ,这只是年。 (请参阅 SimpleDateFormat 文档。)

You're using YYYY in your format specifier, which is week year (as of Java 7, I believe). You want yyyy, which is just "year". (See the SimpleDateFormat documentation.)

我怀疑剩下的日期已经过去了,因为你也试图指定月份和日期,这不是真正的功能星期一年...如果您指定了周周和星期几,可能会给出一些更明智的结果,但只有当您真正意识到使用周年时,我怀疑:)

I suspect the rest of the date was out because you tried to also specify the month and day, which aren't really "features" in the week year... if you'd specified the "week of week year" and day of week, it might have given some more sensible results, but only if you really meant to use week years, which I doubt :)

这篇关于使用SimpleDateFormat.parse()时获取错误的数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆