Products
GG网络技术分享 2025-11-10 15:33 2
在Java中,将Timestamp对象转换为字符串格式通常用SimpleDateFormat类。
java import java.sql.Timestamp; import java.text.SimpleDateFormat;

public class TimestampToStringExample { public static void main { // 获取当前时候戳 Timestamp now = new Timestamp);
// 创建SimpleDateFormat对象,指定日期时候格式
SimpleDateFormat df = new SimpleDateFormat;
// 用format方法将Timestamp对象转换为字符串
String str = df.format;
// 输出转换后的字符串
System.out.println;
}
}
这段代码先说说创建了一个Timestamp对象,表示当前时候。然后创建了一个SimpleDateFormat对象,并指定了日期时候的格式为"yyyy-MM-dd HH:mm:ss"。之后用format方法将Timestamp对象转换为字符串,并将后来啊输出。
Ru果你需要将字符串转换回Timestamp对象, Neng用Timestamp.valueOf方法:
public class StringToTimestampExample { public static void main { // 定义一个日期时候字符串 String str = "2023-04-01 12:00:00";
// 创建SimpleDateFormat对象,指定日期时候格式
SimpleDateFormat df = new SimpleDateFormat;
try {
// 用valueOf方法将字符串转换为Timestamp对象
Timestamp timestamp = Timestamp.valueOf;
// 输出转换后的Timestamp对象
System.out.println;
} catch {
e.printStackTrace;
}
}
这段代码先说说定义了一个日期时候字符串,然后创建了一个SimpleDateFormat对象,并指定了相同的日期时候格式。用valueOf方法将字符串转换为Timestamp对象,并输出转换后的后来啊。
需要注意的是 用valueOf方法时Ru果字符串格式不正确,将会抛出java.text.ParseException异常,所以呢在转换字符串时得捕获这玩意儿异常。
Demand feedback