将 Java 公历转换为字符串

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/24741696/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-14 14:35:58  来源:igfitidea点击:

Convert Java Gregorian Calendar to String

javaxmldomcalendargregorian-calendar

提问by SagittariusA

I have a Book Class and one of its attributes is:

我有一个 Book Class,它的属性之一是:

private Calendar publish_date;

Now I would like to insert a new Book in a library.xml file. So I create a book:

现在我想在 library.xml 文件中插入一本新书。所以我创作了一本书:

Book b = new Book();
b.setPublish_date(new GregorianCalendar(1975, 5, 7));

I need that date to be a String so that I can write it in XML file (using DOM). So I perform:

我需要该日期是一个字符串,以便我可以将它写入 XML 文件(使用 DOM)。所以我执行:

    Element publish_date = doc.createElement("publish_date");
    SimpleDateFormat formatter=new SimpleDateFormat("yyyy MM DD"); 
    publish_date.appendChild(doc.createTextNode(formatter.format(b.getPublish_date())));
    book.appendChild(publish_date);

but this is the error:

但这是错误:

java.lang.IllegalArgumentException: Cannot format given Object as a Date
at java.text.DateFormat.format(DateFormat.java:301)
at java.text.Format.format(Format.java:157)
at fileLock.FileLock.updateLibrary(FileLock.java:127)
at fileLock.FileLock.main(FileLock.java:63)

so which is the correct way to convert a Calendar (Gregorian Calendar) to a string? Thanks

那么将日历(公历)转换为字符串的正确方法是什么?谢谢

采纳答案by rgettman

A SimpleDateFormatcan't format a GregorianCalendar; it can format a Date, so convert it to a Datefirst. You are getting 158as the day, because DDis the day of the year, but dd(lowercase) is the day of month.

ASimpleDateFormat不能格式化GregorianCalendar; 它可以格式化 a Date,因此Date先将其转换为 a 。你得到的158是一天,因为DD是一年中的一天,但dd(小写)是一个月中的一天。

SimpleDateFormat formatter=new SimpleDateFormat("yyyy MM dd");   // lowercase "dd"
publish_date.appendChild(doc.createTextNode(formatter.format(
    b.getPublish_date().getTime() )));

Also, you may have known, you may not have known, but month numbers are 0-11 in Java, so when formatted, month 5is June, so it comes out as 06.

此外,您可能知道,也可能不知道,但是在 Java 中月份数字是 0-11,所以格式化后,月份5是六月,所以它显示为06.

Output:

输出:

1975 06 07

回答by A4L

You need to use Calendar#getTimein order to get the correct argument for SimpleDateformat

您需要使用Calendar#getTime以获得SimpleDateformat的正确参数

publish_date.appendChild(doc.createTextNode(
    formatter.format(b.getPublish_date().getTime())));