在 Java 中将毫秒字符串转换为日期

新手上路,请多包涵

我有一个字符串 x = “1086073200000” 。这基本上是毫秒,我需要将其转换为日期。

要转换我正在使用

DateFormat formatter = new SimpleDateFormat("dd/MM/yyyy");

long tempo1=Long.parseLong(x);
System.out.println(tempo1);  // output is 86073200000 instead of the whole thing
long milliSeconds=1346482800000L;

Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(milliSeconds);
System.out.println(formatter.format(calendar.getTime()));

问题是当我将字符串 x 转换为 long 时,由于 long 的大小限制,一些数字消失了。

如何保留整个字符串。

谢谢。

原文由 jseth 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 507
2 个回答
> double tempo=Double.parseDouble(z);
>
> ```

你为什么要解析你的 `String` 它应该是 `Long` 作为 `Double` ?

尝试使用 `Long.parseLong` :

String x = “1086073200000”

DateFormat formatter = new SimpleDateFormat(“dd/MM/yyyy”);

long milliSeconds= Long.parseLong(x); System.out.println(milliSeconds);

Calendar calendar = Calendar.getInstance(); calendar.setTimeInMillis(milliSeconds); System.out.println(formatter.format(calendar.getTime()));

”`

原文由 Tim Bender 发布,翻译遵循 CC BY-SA 3.0 许可协议

我试过这段代码,它对我有用

public static void main(String[] args) {
    String x = "1086073200000";
    long foo = Long.parseLong(x);
    System.out.println(x + "\n" + foo);

    Date date = new Date(foo);
    DateFormat formatter = new SimpleDateFormat("dd/MM/yyyy");
    System.out.println(formatter.format(date));
}

原文由 enTropy 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题