【问题标题】:Convert integer date time into real date time problem? JAVA [duplicate]将整数日期时间转换为实际日期时间问题? JAVA [重复]
【发布时间】:2020-08-17 13:46:59
【问题描述】:

所以我在将整数日期时间格式转换为 Java 中的普通日期时间格式时遇到了这个问题。 我有这个变量 int DateTime,例如它是:“/Date(1484956800000)/”。我正在尝试将其转换为正常的日期时间并将其显示在屏幕上...

我试过这样..

   String dateAsText = new SimpleDateFormat("MM-dd HH:mm")
                .format(new Date(Integer.parseInt(deals.getDate_time())  * 1000L));

// setting my textView with the string dateAsText
       holder.Time.setText(dateAsText);

【问题讨论】:

  • 看来您的 int/long 值 (1484956800000) 已经是毫秒分辨率的时间戳。尝试转换它而不先乘以 1000L。
  • @ThomasKläger 我删除了 1000L ,但同样的问题..,
  • 同样的问题 — 哪个问题,我想你忘了告诉我们? I downvoted because without a proper and precise problem description we cannot help you.
  • 抱歉,我错过了那个:Integer.parseInt(deals.getDate_time()) 会为 1484956800000 抛出 NumberFormatException,因为 1484956800000 不适合整数范围。您还必须将其替换为 Long.parseLong(deals.getDate_time())

标签: java android-studio date datetime datetime-format


【解决方案1】:

我建议您停止使用过时且容易出错的 java.util 日期时间 API 和 SimpleDateFormat。切换到 modern java.time 日期时间 API 和相应的格式化 API (java.time.format)。从 Trail: Date Time 了解有关现代日期时间 API 的更多信息。

import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;

public class Main {
    public static void main(String[] args) {
        // Obtain an instance of Instant using milliseconds from the epoch of
        // 1970-01-01T00:00:00Z
        Instant instant = Instant.ofEpochMilli(1484956800000L);
        System.out.println(instant);

        // Specify the time-zone
        ZoneId myTimeZone = ZoneId.of("Europe/London");

        // Obtain ZonedDateTime out of Instant
        ZonedDateTime zdt = instant.atZone(myTimeZone);

        // Obtain LocalDateTime out of ZonedDateTime
        // Note that LocalDateTime throws away the important information of time-zone
        LocalDateTime ldt = zdt.toLocalDateTime();
        System.out.println(ldt);

        // Custom format
        String dateAsText = ldt.format(DateTimeFormatter.ofPattern("MM-dd HH:mm"));
        System.out.println(dateAsText);
    }
}

输出:

2017-01-21T00:00:00Z
2017-01-21T00:00
01-21 00:00

如果你仍然想使用设计不佳的遗留java.util.Date,你可以这样做:

import java.text.SimpleDateFormat;
import java.util.Date;

public class Main {
    public static void main(String[] args) {
        Date date = new Date(1484956800000L);
        System.out.println(date);

        // Custom format
        String dateAsText = new SimpleDateFormat("MM-dd HH:mm").format(date);
        System.out.println(dateAsText);
    }
}

输出:

Sat Jan 21 00:00:00 GMT 2017
01-21 00:00

【讨论】:

    猜你喜欢
    • 2012-05-15
    • 1970-01-01
    • 1970-01-01
    • 2016-07-15
    • 2011-07-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-08-14
    相关资源
    最近更新 更多