Java.sql.Timestamp format to string

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

yyyymmdd

I know that doing this with String pretty simple, like this:

 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 need to work with a Timestamp object.

+6
source share
3 answers

You can do something like this:

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

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

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

The analysis is almost the same; it can be built using the millis view:

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

Using www.joda.org/joda-time/

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

All Articles