Java 将双精度格式转换为日期格式
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/42666270/
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
Java convert double to date format
提问by Rufat
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+firebase 中做了一个小应用程序,现在我正在尝试连接 android。在 ios 中,我将日期保存为双精度(例如:-242528463.775282),但随后我尝试在 java 中检索相同的双精度它给了我另一个日期。
in IOS - 01.07.2009 in Java - 29.12.1969
在 IOS - 01.07.2009 在 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);
Is it possible to convert double to date without converting to long?
是否可以将double转换为date而不转换为long?
回答by Florent Bayle
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
表示从现在开始的秒数,并且Date
Java 中的构造函数期望自 01-01-1970 以来的毫秒数,您必须乘以您的数字以获得毫秒数 ( * 1000
) 并从自 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);
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
.
但是,存储日期方式的问题在于,如果您今天和明天调用此代码,它不会返回相同的日期,因为当前时间正在更改。您应该使用timeIntervalSince1970
而不是timeIntervalSinceNow
.
回答by Alan
Have a play around with statements below. In particular;
long myLong = todate.getTime();
and store this to interpret later perhaps?
试试下面的语句。特别是; long myLong = todate.getTime();
并将其存储起来以便稍后解释?
import java.text.SimpleDateFormat;
import java.util.Date;
public class dateConvertDouble {
public static void main(String[] args) {
Date todate = new Date();
System.out.println(todate);
long myLong = todate.getTime();
System.out.println(myLong);
double myDouble = (double)myLong;
System.out.println(myDouble);
String myDateStr = new SimpleDateFormat("dd-MM-yyyy").format(myLong);
System.out.println(myDateStr);
}
}