将java.sql.Timestamp格式化为字符串。

31

是否可以将java.sql.Timestamp转换/格式化为以下格式的字符串:

yyyyMMdd

我知道使用一个String很容易实现,例如:

String dateString = "2016-02-03 00:00:00.0";
Date date = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.S").parse(dateString);
String formattedDate = new SimpleDateFormat("yyyyMMdd").format(date);

但是,我必须使用Timestamp对象工作。

4个回答

39

java.sql.Timestamp 扩展了 java.util.Date,因此您可以以完全相同的方式格式化它:

String formattedDate = new SimpleDateFormat("yyyyMMdd").format(date);

解析几乎相同,您可以使用其“millis”表示构造它:

Timestamp timestamp = new Timestamp(new SimpleDateFormat("yyyyMMdd").parse(formattedDate).getTime());

29

你可以这样做:

Timestamp ts = ...;
Date date = new Date();
date.setTime(ts.getTime());
String formattedDate = new SimpleDateFormat("yyyyMMdd").format(date);

1
时间戳扩展日期。 - Kashyap
@Kashyap:我不太明白你的评论。 - npinti
4
SimpleDateFormat.format() 方法可以接受 Timestamp 类型的参数,无需创建新的 Date 对象。 - Kashyap
2
这种方法是糟糕的代码,效率低下。请参考@Robert Bräutigam的更好答案。 - Codi
1
有不同的“日期”类,您能具体说明您指的是哪个“日期”类吗? - Sim
@Sim:这是一个非常古老的帖子,然而我很可能是在提到java.util.Date类。 - npinti

4

使用(并不是那么)新的java.time包:

private static final DateTimeFormatter FORMATTER = DateTimeFormatter.ofPattern("yyyyMMdd");

String convert(Timestamp ts) {
    return ts.toLocalDateTime().format(FORMATTER);
}

3
使用www.joda.org/joda-time/
public static String timestampAsString(Timestamp timestamp) {
    return DateTimeFormat.forPattern("yyyyMMdd").print(timestamp.getTime());
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接