Reputation: 133
I am using System.currentTimeMillis() and adding the value of a day/week/month based on user input. How can I convert this to java.sql.Timestamp so I can save it in mysql? Thanks.
Upvotes: 11
Views: 44045
Reputation: 6361
This code snippet is used to convert timestamp in milliseconds to Unix based java.sql.Timestamp
/**
* Convert the epoch time to TimeStamp
*
* @param timestampInString timestamp as string
* @return date as timestamp
*/
public static Timestamp getTimestamp(String timestampInString) {
if (StringUtils.isNotBlank(timestampInString) && timestampInString != null) {
Date date = new Date(Long.parseLong(timestampInString));
DateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
format.setTimeZone(TimeZone.getTimeZone("Etc/UTC"));
String formatted = format.format(date);
Timestamp timeStamp = Timestamp.valueOf(formatted);
return timeStamp;
} else {
return null;
}
}
Upvotes: 0
Reputation: 4179
Use constructor.
new Timestamp(System.currentTimeMillis())
http://docs.oracle.com/javase/7/docs/api/java/sql/Timestamp.html#Timestamp(long)
Upvotes: 25