問題描述
我在 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
.
這篇關于Java將double轉換為日期格式的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!