将GregorianCalendar与SimpleDateFormat一起使用 [英] Using GregorianCalendar with SimpleDateFormat

查看:142
本文介绍了将GregorianCalendar与SimpleDateFormat一起使用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我一直在讨论这个(应该是)简单的练习,让程序将日期字符串转换为GregorianCalendar对象,格式化它,并在完成时将其作为字符串再次返回。

So I've been racking my brain over this (should-be) simple exercise to make the program turn a date string into a GregorianCalendar object, format it, and return it again as a string when it's done.

这是一个程序的最后一点,从文件中获取文本,将其分解为单个记录,然后将记录分成单独的数据和分配他们是一个人的对象。

This is the last little bit of a program that takes in a chuck of text from a file, breaks it down into individual records, then breaks the records into individual pieces of data and assigns them to a person object.

我已经在多个地方检查了代码,代码完全按照预期的方式进行,直到我调用格式函数,这会抛出IllegalArgumentException。 GergorianCalendar对象被赋予应该分配的值(虽然打印它是另一个完整的故事,如下所示......),但格式不接受该对象进行格式化。

I've checked the code in multiple places and the code does exactly what it's supposed to be doing up until I call the format function, which throws an IllegalArgumentException. The GergorianCalendar object is assigned the values it is supposed to be assigned (though printing it is, again, a whole other story as seen below...), yet the format will not accept the object for formatting.

不幸的是,教练不太确定如何使用GregorianCalendar和SimpleDateFormat(但指派我们使用它们)并说只是谷歌它......我试过了,什么都没有我发现有帮助。

Unfortunately, the instructor wasn't too sure of how to use the GregorianCalendar and SimpleDateFormat (yet assigned us to work with them) and said "Just Google it"... I tried, and nothing I've found has helped.

到目前为止我的代码是:

The code I have so far is:

public class DateUtil {

    public static GregorianCalendar convertFromDMY(String dd_mm_yy) throws ParseException{

        // this actually works, got rid of the original code idea
        String[] splitDate = dd_mm_yy.split("-");
        int days = Integer.parseInt(splitDate[0]);
        int month = Integer.parseInt(splitDate[1]);
        int year = Integer.parseInt(splitDate[2]);

        // dates are going in right, checked in print statement,
        // but the object is not getting formatted...
        GregorianCalendar dateConverted = new GregorianCalendar(year, month, days);
        format(dateConverted);
        return dateConverted;
    }

    public static String format(GregorianCalendar date){

        SimpleDateFormat fmt = new SimpleDateFormat("dd-MMM-yyyy");
        String dateFormatted = fmt.format(date);
        return dateFormatted;
    }
}

我得到的错误是:


Exception in thread "main" java.lang.IllegalArgumentException: Cannot format given Object >as a Date

    at java.text.DateFormat.format(DateFormat.java:281)
    at java.text.Format.format(Format.java:140)
    at lab2.DateUtil.format(DateUtil.java:26) 
    at lab2.DateUtil.convertFromDMY(DateUtil.java:19)
    at lab2.Lab2.createStudent(Lab2.java:75)
    at lab2.Lab2.main(Lab2.java:34)

还有一件事,我甚至使用GregorianCalendar吗?当我打印出该对象的值(应该是一个正确的日期?)我得到这个:

And another thing, am I even using the GregorianCalendar right?? When I print out that object's value (should be getting a date right?) I get this:


java.util.GregorianCalendar [time = ?,areFieldsSet =假,areAllFieldsSet =假,宽松= TRUE,区= sun.util.calendar.ZoneInfo [ID = 美洲/温哥华,偏移量= -28800000,dstSavings = 3600000,useDaylight = TRUE,转换= 189,lastRule = java.util.SimpleTimeZone中[ID =美国/温哥华,偏移= -28800000,dstSavings = 3600000,useDaylight =真,startYear = 0,STARTMODE = 3,startMonth = 2,朝九特派= 8,startDayOfWeek = 1,开始时间= 7200000, startTimeMode = 0,endMode = 3,endMonth = 10,endday指定= 1,一个endDayOfWeek = 1,结束时间= 7200000,endTimeMode = 0]],Firstdayofweek可= 1,minimalDaysInFirstWeek = 1,ERA = ?, YEAR = 1985,MONTH = 4, WEEK_OF_YEAR = ?, WEEK_OF_MONTH = ?, DAY_OF_MONTH = 22,DAY_OF_YEAR = ?, DAY_OF_WEEK = ?, DAY_OF_WEEK_IN_MONTH = ?, AM_PM = 0,HOUR = 0,HOUR_OF_DAY = 0,MINUTE = 0,SECOND = 0,微差= ?, ZONE_OFFSET = ?,DST_OFFSET =?]

java.util.GregorianCalendar[time=?,areFieldsSet=false,areAllFieldsSet=false,lenient=true,zone=sun.util.calendar.ZoneInfo[id="America/Vancouver",offset=-28800000,dstSavings=3600000,useDaylight=true,transitions=189,lastRule=java.util.SimpleTimeZone[id=America/Vancouver,offset=-28800000,dstSavings=3600000,useDaylight=true,startYear=0,startMode=3,startMonth=2,startDay=8,startDayOfWeek=1,startTime=7200000,startTimeMode=0,endMode=3,endMonth=10,endDay=1,endDayOfWeek=1,endTime=7200000,endTimeMode=0]],firstDayOfWeek=1,minimalDaysInFirstWeek=1,ERA=?,YEAR=1985,MONTH=4,WEEK_OF_YEAR=?,WEEK_OF_MONTH=?,DAY_OF_MONTH=22,DAY_OF_YEAR=?,DAY_OF_WEEK=?,DAY_OF_WEEK_IN_MONTH=?,AM_PM=0,HOUR=0,HOUR_OF_DAY=0,MINUTE=0,SECOND=0,MILLISECOND=?,ZONE_OFFSET=?,DST_OFFSET=?]

年,月和day_of_month值都是正确的,因为它们是我通过的数字进入它的创造。

The year, month and day_of_month values are all correct as they are the numbers I passed into the creation of it.

思考,建议,我甚至关闭?

Thoughts, suggestions, am I even close?

编辑

原始问题已解决(谢谢assylias!)但我仍然无法正常打印,因为这两个功能没有链接且要求是从person对象打印出的GregorianCalendar日期值(作为birthdate是GregorianCalendar)。

original issues cleared up (thank you assylias!) but I still can't print properly because the two functions aren't linked and the requirements are to have a GregorianCalendar date value printed out from the person object (as birthdate is a GregorianCalendar).

更新代码:

public class DateUtil {

    static SimpleDateFormat fmt = new SimpleDateFormat("dd-MMM-yyyy");

    public static GregorianCalendar convertFromDMY(String dd_mm_yy) throws ParseException{

        // this actually works, got rid of the original code idea
        String[] splitDate = dd_mm_yy.split("-");
        int days = Integer.parseInt(splitDate[0]);
        int month = (Integer.parseInt(splitDate[1]) - 1);
        int year = Integer.parseInt(splitDate[2]);

        // dates go in properly
        GregorianCalendar dateConverted = new GregorianCalendar(year, month, days);
        String finalDate = format(dateConverted);
        return ;
    }

    public static String format(GregorianCalendar date) throws ParseException{

       fmt.setCalendar(date);
        String dateFormatted = fmt.format(date.getTime());
        System.out.println(dateFormatted);
        return dateFormatted;
    }

}

上次修改

好吧所以我似乎是个白痴,并且不需要将两个DateUtil函数链接在一起,而是串联使用它们。首先,将birthdate转换为GregorianCalendar并将其存储在person对象中。然后在print语句中只需告诉程序在打印日期时格式化该日期。问题解决了。现在所有的工作都按照规格进行了,我感觉非常愚蠢,因为在最后一天左右,我在DateUtil课程中像水鱼一样甩尾,试图让它们同时工作。

Ok so it seems that I'm an idiot and DIDN'T need to link the two DateUtil functions together, but use them in tandem. First, convert the birthdate to a GregorianCalendar and store it in the person object. Then in the print statement just simply tell the program to format that date as it's being printed. Problem was solved. All works according to specifications now, and I feel that much stupider because I was flailing like a fish out of water for the last day or so with the DateUtil class, trying to get them to work at the same time.

感谢所有关于正确使用日期的帮助!

Thanks for the help all on getting the date go in properly!

推荐答案

SimpleDateFormat #format 方法将日期作为参数。您可以通过调用 getTime 日历获取日期 >方法:

SimpleDateFormat#format method takes a Date as a parameter. You can get a Date from a Calendar by calling its getTime method:

public static String format(GregorianCalendar calendar){
    SimpleDateFormat fmt = new SimpleDateFormat("dd-MMM-yyyy");
    fmt.setCalendar(calendar);
    String dateFormatted = fmt.format(calendar.getTime());
    return dateFormatted;
}

另请注意,月份从0开始,因此您可能意味着:

Also note that the months start at 0 so you probably meant:

int month = Integer.parseInt(splitDate[1]) - 1;

这篇关于将GregorianCalendar与SimpleDateFormat一起使用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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