在 Java 中将毫秒转换为时间戳
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/21798710/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Converting milliseconds to Timestamp in Java
提问by user3313539
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.
我正在使用 System.currentTimeMillis() 并根据用户输入添加天/周/月的值。如何将其转换为 java.sql.Timestamp 以便将其保存在 mysql 中?谢谢。
采纳答案by Nailgun
Use constructor.
使用构造函数。
new Timestamp(System.currentTimeMillis())
http://docs.oracle.com/javase/7/docs/api/java/sql/Timestamp.html#Timestamp(long)
http://docs.oracle.com/javase/7/docs/api/java/sql/Timestamp.html#Timestamp(long)
回答by Khader M A
This code snippet is used to convert timestamp in milliseconds to Unix based java.sql.Timestamp
此代码片段用于将时间戳(以毫秒为单位)转换为基于 Unix 的 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;
}
}