問題描述
我在將字符串日期解析為 Date
對象時遇到了一些麻煩.我使用 DateFormat
來解析字符串,當我打印日期的值時,它給出了我所期望的.
I am having a bit of trouble parsing a string date to a Date
object. I use a DateFormat
to parse the string, and when I print the value of the date, it gives me what I expect.
但是當我嘗試獲取日期、月份或年份時,它給了我錯誤的值.例如,年份是 2011 年,但是當我執行 .getYear()
時,它給了我 111.我不知道為什么會這樣.以下是相關代碼段:
But when I try get the day, the month or the year it gives me the wrong values. For instance, the year is 2011, but when I do .getYear()
it gives me 111. I have no idea why this is happening. Here is the relevant code segment:
Date dateFrom = null;
String gDFString = g.getDateFrom();
System.out.println(gDFString);
DateFormat df = new SimpleDateFormat("dd/MM/yyyy");
try {
dateFrom = df.parse("04/12/2011");
System.out.println(dateFrom);
System.out.println(dateFrom.getYear());
} catch (ParseException e) {
e.printStackTrace();
}
當我輸出 dateFrom
時,我得到 Sun Dec 04 00:00:00 GMT 2011
,這是您所期望的.但是打印 .getYear()
會返回 111
.
When I out print dateFrom
, I get Sun Dec 04 00:00:00 GMT 2011
, which is what you would expect. But printing .getYear()
returns 111
.
我需要能夠為時間序列圖獲取日期的日、月和年.
I need to be able to get the day, month and year of the date for a time series graph.
推薦答案
這些方法已棄用.相反,請使用 Calendar 類.
Those methods have been deprecated. Instead, use the Calendar class.
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
public final class DateParseDemo {
public static void main(String[] args){
final DateFormat df = new SimpleDateFormat("MM/dd/yyyy");
final Calendar c = Calendar.getInstance();
try {
c.setTime(df.parse("04/12/2011"));
System.out.println("Year = " + c.get(Calendar.YEAR));
System.out.println("Month = " + (c.get(Calendar.MONTH)));
System.out.println("Day = " + c.get(Calendar.DAY_OF_MONTH));
}
catch (ParseException e) {
e.printStackTrace();
}
}
}
輸出:
Year = 2011
Month = 3
Day = 12
<小時>
對于 month 字段,這是從 0 開始的.這意味著一月 = 0 和十二月 = 11.正如 javadoc 所述,
And as for the month field, this is 0-based. This means that January = 0 and December = 11. As stated by the javadoc,
get 和 set 的字段編號,表示月份.這是一個特定于日歷的值.公歷一年的第一個月而儒略歷是JANUARY
,即0
;最后取決于一年中的月數.
Field number for get and set indicating the month. This is a calendar-specific value. The first month of the year in the Gregorian and Julian calendars is
JANUARY
which is0
; the last depends on the number of months in a year.
這篇關于為什么 Java 的 Date.getYear() 返回 111 而不是 2011?的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!