Java 时间戳转换字符串:示例代码和步骤
Java 中可以使用 java.text.SimpleDateFormat 类来将时间戳转换为字符串。以下是一个示例代码:
import java.text.SimpleDateFormat;
import java.util.Date;
public class TimestampToString {
public static void main(String[] args) {
long timestamp = 1617062400000L; // 时间戳,单位为毫秒
// 创建 SimpleDateFormat 对象,指定日期时间的格式
SimpleDateFormat sdf = new SimpleDateFormat('yyyy-MM-dd HH:mm:ss');
// 使用 format 方法将时间戳转换为字符串
String dateString = sdf.format(new Date(timestamp));
System.out.println(dateString);
}
}
输出结果为:2021-03-30 00:00:00
在示例代码中,我们首先创建了一个 SimpleDateFormat 对象 sdf,指定了日期时间的格式为 'yyyy-MM-dd HH:mm:ss'。然后使用 format 方法将时间戳转换为字符串,传入 Date 对象 new Date(timestamp),其中 timestamp 为要转换的时间戳。最后将转换后的字符串输出到控制台。
步骤总结:
- 创建
SimpleDateFormat对象,指定日期时间格式。 - 使用
format方法将时间戳转换为字符串,传入Date对象。 - 输出转换后的字符串。
原文地址: https://www.cveoy.top/t/topic/qlSF 著作权归作者所有。请勿转载和采集!