Java convert double to date format(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
.
这篇关于Java将double转换为日期格式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:Java将double转换为日期格式


基础教程推荐
- 从 python 访问 JVM 2022-01-01
- 如何在 Spring @Value 注解中正确指定默认值? 2022-01-01
- 如何在 JFrame 中覆盖 windowsClosing 事件 2022-01-01
- 在 Java 中创建日期的正确方法是什么? 2022-01-01
- 不推荐使用 Api 注释的描述 2022-01-01
- 多个组件的复杂布局 2022-01-01
- 验证是否调用了所有 getter 方法 2022-01-01
- Java Swing计时器未清除 2022-01-01
- Java 实例变量在两个语句中声明和初始化 2022-01-01
- 大摇大摆的枚举 2022-01-01