Java将双精度转换为日期格式 [英] Java convert double to date format
问题描述
我在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中-2009年1月7日 在Java中-1969年12月29日
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);
是否可以将double转换为date而不转换为long?
Is it possible to convert double to date without converting to long?
推荐答案
由于您的double
表示从现在开始的秒数,并且Java中的Date
构造函数期望从01-开始的毫秒数1970年1月1日,您必须将数字乘以得到毫秒数(* 1000
),然后从1970年1月1日以来的当前毫秒数(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将双精度转换为日期格式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!