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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/35170620/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-11 16:23:59  来源:igfitidea点击:

Format java.sql.Timestamp into a String

java

提问by

Is it possible to convert/format java.sql.Timestmapinto a String that has the following format:

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

yyyyMMdd

YYYYMMDD

I know that doing it with a Stringis fairly simple e.g:

我知道用 a 做它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);

But, I have to work with the Timestampobject.

但是,我必须与Timestamp对象一起工作。

采纳答案by npinti

You could do something like so:

你可以这样做:

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

回答by Robert Br?utigam

The java.sql.Timestampextends java.util.Date, so you can format it exactly the same way:

java.sql.Timestamp扩展java.util.Date,这样你就可以完全相同的方式对其进行格式化:

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

Parsing is almost the same, you can construct it using its "millis" representation:

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

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

回答by Igor Vukovi?

Using www.joda.org/joda-time/

使用www.joda.org/joda-time/

public static String timestampAsString(Timestamp timestamp) {
    return DateTimeFormat.forPattern("yyyyMMdd").print(timestamp.getTime());
}