32

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

yyyyMMdd

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

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 Timestamp object.

4 Answers 4

40

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

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());
30

You could do something like so:

Timestamp ts = ...;
Date date = new Date();
date.setTime(ts.getTime());
String formattedDate = new SimpleDateFormat("yyyyMMdd").format(date);
6
  • 1
    Timestamp extends Date
    – Kashyap
    Commented Feb 9, 2018 at 14:48
  • @Kashyap: I do not quite get your comment.
    – npinti
    Commented Feb 10, 2018 at 11:26
  • 4
    SimpleDateFormat.format() will accept type Timestamp. No need to create a new Date().
    – Kashyap
    Commented Feb 10, 2018 at 16:41
  • 2
    This approach is bad code, inefficient. Please see better answer by @Robert Bräutigam.
    – Codi
    Commented Nov 13, 2018 at 7:37
  • 1
    there are different Date classes, can you specify which Date class you mean?
    – Sim
    Commented Feb 19, 2021 at 9:13
6

Using the (not so) new java.time package:

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

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

Using www.joda.org/joda-time/

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