要将 long 类型的时间戳字段转换为 yyyy-MM-dd 格式,可以使用 Java 的 SimpleDateFormat 类来实现。以下是一个示例代码:

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

public class TimestampToDate {
    public static void main(String[] args) {
        long timestamp = 1617897600000L; // 示例时间戳,单位为毫秒

        // 创建 SimpleDateFormat 对象,指定输出格式为 yyyy-MM-dd
        SimpleDateFormat sdf = new SimpleDateFormat('yyyy-MM-dd');

        // 使用 Date 的构造函数将时间戳转换为 Date 对象
        Date date = new Date(timestamp);

        // 使用 SimpleDateFormat 的 format 方法将 Date 对象转换为指定格式的字符串
        String formattedDate = sdf.format(date);

        System.out.println('Formatted date: ' + formattedDate);
    }
}

输出结果为:

Formatted date: 2021-04-09

在上述代码中,我们首先创建了一个 SimpleDateFormat 对象,并通过构造方法传入了指定的输出格式 'yyyy-MM-dd'。然后,使用 Date 的构造函数将 long 类型的时间戳转换为 Date 对象。最后,使用 SimpleDateFormat 的 format 方法将 Date 对象转换为指定格式的字符串。

Java 将 Long 类型时间戳转换为 yyyy-MM-dd 格式

原文地址: https://www.cveoy.top/t/topic/pe6P 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录