Android 将日期转换为毫秒
Android Date worng conversion date into millis
我遇到了这样的问题。我保存了一个Date (yyyy,mm,dd
)。从这个日期开始,我需要得到它的 millisec
表示,但是当我调用 getTime()
时,它给了我错误的时间。问题出在哪里?
Example :
Date testDate= new Date (2015,5,11);
当我尝试调用此日期毫秒时,testDate.getTime()
result=61392117600000, but it must be result=1433970000000
注意:5 表示 Jun,因为它从 0 开始计算
因为在包java.util;
下的DateClass中日期方法add year from 1900
as
/**
* Constructs a new {@code Date} initialized to midnight in the default {@code TimeZone} on
* the specified date.
*
* @param year
* the year, 0 is 1900.
* @param month
* the month, 0 - 11.
* @param day
* the day of the month, 1 - 31.
*
* @deprecated Use {@link GregorianCalendar#GregorianCalendar(int, int, int)} instead.
*/
@Deprecated
public Date(int year, int month, int day) {
GregorianCalendar cal = new GregorianCalendar(false);
cal.set(1900 + year, month, day);
milliseconds = cal.getTimeInMillis();
}
所以你需要改变
Date testDate= new Date (2015,5,11);
到
Date testDate= new Date (115,5,11);
推荐的方法是使用 SimpleDateFormat
,如下所示。
Android convert date and time to milliseconds
year - the year minus 1900; must be 0 to 8099. (Note that 8099 is 9999 minus 1900.)
来自 JavaDoc (http://docs.oracle.com/javase/7/docs/api/java/sql/Date.html)
因此,您将使用 2015 - 1900 = 115 作为年份参数,而不是 2015 年
我遇到了这样的问题。我保存了一个Date (yyyy,mm,dd
)。从这个日期开始,我需要得到它的 millisec
表示,但是当我调用 getTime()
时,它给了我错误的时间。问题出在哪里?
Example :
Date testDate= new Date (2015,5,11);
当我尝试调用此日期毫秒时,testDate.getTime()
result=61392117600000, but it must be result=1433970000000
注意:5 表示 Jun,因为它从 0 开始计算
因为在包java.util;
下的DateClass中日期方法add year from 1900
as
/**
* Constructs a new {@code Date} initialized to midnight in the default {@code TimeZone} on
* the specified date.
*
* @param year
* the year, 0 is 1900.
* @param month
* the month, 0 - 11.
* @param day
* the day of the month, 1 - 31.
*
* @deprecated Use {@link GregorianCalendar#GregorianCalendar(int, int, int)} instead.
*/
@Deprecated
public Date(int year, int month, int day) {
GregorianCalendar cal = new GregorianCalendar(false);
cal.set(1900 + year, month, day);
milliseconds = cal.getTimeInMillis();
}
所以你需要改变
Date testDate= new Date (2015,5,11);
到
Date testDate= new Date (115,5,11);
推荐的方法是使用 SimpleDateFormat
,如下所示。
Android convert date and time to milliseconds
year - the year minus 1900; must be 0 to 8099. (Note that 8099 is 9999 minus 1900.)
来自 JavaDoc (http://docs.oracle.com/javase/7/docs/api/java/sql/Date.html)
因此,您将使用 2015 - 1900 = 115 作为年份参数,而不是 2015 年