Java将double转换为日期格式
我在 ios+firebase 中做了一个小应用程序,现在我正在尝试连接 android.在 ios 中,我将日期保存为双精度(例如:-242528463.775282),但随后我尝试在 java 中检索相同的双精度,它给了我另一个日期.
I have made a little app in ios+firebase, now I am trying to connect android. In ios I save date as double (for example: -242528463.775282), but then I trying to retrieve same double in java it giving me another date.
在 IOS - 01.07.2009在 Java 中 - 29.12.1969
in IOS - 01.07.2009 in Java - 29.12.1969
double myDouble = date;
long myLong = (long) (myDouble);
System.out.println(myLong);
Date itemDate = new Date(itemLong);
String myDateStr = new SimpleDateFormat("dd-MM-yyyy").format(itemDate);
editTextDate.setText(myDateStr);
是否可以在不转换为 long 的情况下将 double 转换为 date?
Is it possible to convert double to date without converting to long?
推荐答案
由于你的 double
代表你从现在开始日期的秒数,而 Date
构造函数在Java 预计自 01-01-1970 以来的毫秒数,您必须乘以您的数字以获得毫秒数 (* 1000
),然后从 01-01 以来的当前毫秒数中减去该数-1970(System.currentTimeMillis()
):
Since your double
represents the number of seconds of you date from now, and the Date
constructor in Java is expecting a number of milliseconds since 01-01-1970, you have to multiply your number to get a number of milliseconds (* 1000
) and substract that from the current number of milliseconds since 01-01-1970 (System.currentTimeMillis()
):
double myDouble = -242528463.775282;
long myLong = System.currentTimeMillis() + ((long) (myDouble * 1000));
System.out.println(myLong);
Date itemDate = new Date(myLong);
String myDateStr = new SimpleDateFormat("dd-MM-yyyy").format(itemDate);
System.out.println(myDateStr);
但是,您存储日期的方式的问题是,如果您今天和明天调用此代码,它将不会返回相同的日期,因为当前时间正在改变.您应该使用 timeIntervalSince1970
而不是 timeIntervalSinceNow
.
But, the problem with the way you store your dates is that if you are calling this code today and tomorrow it will not return the same date, as the current time is changing. You should use timeIntervalSince1970
instead of timeIntervalSinceNow
.
相关文章