Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Format java.sql.Timestamp into a String

Tags:

java

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.


2 Answers

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());
like image 140
Robert Bräutigam Avatar answered Sep 04 '25 21:09

Robert Bräutigam


You could do something like so:

Timestamp ts = ...;
Date date = new Date();
date.setTime(ts.getTime());
String formattedDate = new SimpleDateFormat("yyyyMMdd").format(date);
like image 29
npinti Avatar answered Sep 04 '25 21:09

npinti



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!