Java将double转换为日期格式

Java convert double to date format(Java将double转换为日期格式)
本文介绍了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转换为日期格式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

本站部分内容来源互联网,如果有图片或者内容侵犯了您的权益,请联系我们,我们会在确认后第一时间进行删除!

相关文档推荐

quot;Char cannot be dereferencedquot; error(“Char 不能被取消引用错误)
Java Switch Statement - Is quot;orquot;/quot;andquot; possible?(Java Switch 语句 - 是“或/“和可能的?)
Java Replace Character At Specific Position Of String?(Java替换字符串特定位置的字符?)
What is the type of a ternary expression with int and char operands?(具有 int 和 char 操作数的三元表达式的类型是什么?)
Read a text file and store every single character occurrence(读取文本文件并存储出现的每个字符)
Why do I need to explicitly cast char primitives on byte and short?(为什么我需要在 byte 和 short 上显式转换 char 原语?)