แปลงเวลาวันที่เป็นจำนวนเต็มเป็นปัญหาวันเวลาจริงหรือไม่? JAVA [ซ้ำ]

Aug 17 2020

ดังนั้นฉันจึงมีปัญหานี้ในการแปลงรูปแบบ Integer DateTime เป็นรูปแบบ DateTime ปกติใน 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);

คำตอบ

1 LiveandLetLive Aug 17 2020 at 15:08

ผมแนะนำให้คุณหยุดใช้ล้าสมัยและผิดพลาดได้ง่ายjava.utilวันเวลาของ API SimpleDateFormatและ เปลี่ยนไปใช้ API วันที่และเวลาที่ทันสมัย java.timeและ API การจัดรูปแบบที่สอดคล้องกัน ( java.time.format) เรียนรู้เพิ่มเติมเกี่ยวกับ API วันที่เวลาที่ทันสมัยจากTrail: วันที่เวลา

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