使用GregorianCalendar和SimpleDateFormat

23 浏览
0 Comments

使用GregorianCalendar和SimpleDateFormat

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

这是一个从文件中获取一段文本的程序的最后一部分,将其拆分为单个记录,然后将记录拆分为单个数据片段并将它们分配给一个人对象。

我在多个地方检查了代码,代码在我调用格式化函数之前确切地执行了它应该执行的操作,但是格式化不接受对象进行格式化。

不幸的是,讲师对如何使用GregorianCalendarSimpleDateFormat并不十分确定(但是指定我们使用它们),并且说:“只需Google…”我已经尝试了,没有找到有用的信息。

到目前为止,我所拥有的代码是:

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?当我打印出该对象的值(应该获取日期对吧?)时,我得到了以下结果:

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 = ?]

年、月和日数据的值都是正确的,因为它们是我传递到创建它的代码中的数字。

想法、建议,我离正确答案还有多远?

编辑

原先的问题解决了(谢谢assylias!),但我仍无法正确打印,因为两个功能没有链接,并且要求从 person 对象(因为 birthdate 是一个 GregorianCalendar)中打印一个 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 函数链接在一起,而是并列使用它们。首先,将出生日期转换为 GregorianCalendar 并将其存储在 person 对象中。然后,在打印语句中,只需简单地告诉程序在打印时格式化该日期即可。问题得到解决。所有的工作都按照规格完成了,而我感到越来越愚蠢,因为在过去的一天左右,我一直在像一条在水中无助的鱼一样拼命地尝试让 DateUtil 类一起工作。

感谢大家对日期正确输入方面的帮助!

admin 更改状态以发布 2023年5月24日
0
0 Comments

\n\n为什么有这样的复杂性?\n\n

public static GregorianCalendar convertFromDMY(String dd_mm_yy) throws ParseException 
{
    SimpleDateFormat fmt = new SimpleDateFormat("dd-MMM-yyyy");
    Date date = fmt.parse(dd_mm_yy);
    GregorianCalendar cal = GregorianCalendar.getInstance();
    cal.setTime(date);
    return cal;
}

0
0 Comments

SimpleDateFormat.format() 方法需要一个 Date 参数。你可以通过调用 Calendar 对象的 getTime() 方法获取一个 Date

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开始,所以你可能想要表示的是:

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

0