整数の日時を実際の日時の問題に変換しますか?JAVA [複製]

Aug 17 2020

そのため、Javaで整数DateTime形式を通常のDateTime形式に変換する際にこの問題が発生します。私はこの変数intDateTimeを持っています、例えばそれは: "/ 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);

回答

1 LiveandLetLive Aug 17 2020 at 15:08

古くてエラーが発生しやすい日時APIとの使用をやめることをお勧めします。最新の日時APIと対応するフォーマットAPIに切り替えます()。Trail: DateTimeから最新の日時APIの詳細をご覧ください。java.utilSimpleDateFormat java.timejava.time.format

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