下面是一个示例代码,演示了如何将Java long类型的时间戳转换为年月日时分秒的格式:

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

public class TimestampConverter {
    public static void main(String[] args) {
        // 输入时间戳(以毫秒为单位)
        long timestamp = 1612345678901L;

        // 创建SimpleDateFormat对象,设置日期格式
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

        // 将时间戳转换为Date对象
        Date date = new Date(timestamp);

        // 使用SimpleDateFormat格式化Date对象,得到年月日时分秒的字符串
        String formattedDateTime = sdf.format(date);

        // 输出格式化后的字符串
        System.out.println(formattedDateTime);
    }
}

在上面的示例代码中,我们使用了SimpleDateFormat类来进行时间格式化。SimpleDateFormat是一个用于格式化和解析日期时间的类,可以根据指定的模式将日期时间转换为字符串,或将字符串解析为日期时间。

在上面的示例中,我们创建了一个SimpleDateFormat对象,并将日期格式设置为"yyyy-MM-dd HH:mm:ss",表示年月日时分秒的格式。然后,我们使用SimpleDateFormatformat()方法将Date对象格式化为字符串。

最后,我们将格式化后的字符串输出到控制台,结果将是类似于"2021-02-03 12:34:56"的格式

Java long时间戳转年月日时分秒格式 代码示例

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

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