Collectives™ on Stack Overflow
Find centralized, trusted content and collaborate around the technologies you use most.
Learn more about Collectives
Teams
Q&A for work
Connect and share knowledge within a single location that is structured and easy to search.
Learn more about Teams
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.
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());
Using www.joda.org/joda-time/
public static String timestampAsString(Timestamp timestamp) {
return DateTimeFormat.forPattern("yyyyMMdd").print(timestamp.getTime());
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);
Thanks for contributing an answer to Stack Overflow!
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.