我正在使用System.currentTimeMillis()并基于用户输入添加一天/一周/一月的值。我怎样才能将其转换为java.sql.Timestamp,以便我可以将它保存在MySQL中?谢谢。将毫秒转换为Java中的时间戳
1
A
回答
6
使用构造函数。
new Timestamp(System.currentTimeMillis())
http://docs.oracle.com/javase/7/docs/api/java/sql/Timestamp.html#Timestamp(long)
0
使用DateFormat
例如 -
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.*;
public class Example {
public static void main (String [] args) {
long currentDateTime = System.currentTimeMillis();
Date currentDate = new Date(currentDateTime);
DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
System.out.println(dateFormat.format(currentDate));
}
}
输出:
2014-02-15 18:28:59
0
该代码段用于时间戳转换以毫秒为单位基于Unix的java.sql。时间戳
/**
* 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;
}
}
相关问题
- 1. 将时间戳转换为毫秒 - MATLAB
- 2. 如何在毫秒中将时间戳转换为毫秒
- 3. 将时间转换为秒+毫秒秒
- 4. java将时间戳以秒为单位转换为以毫秒为单位的时间戳
- 5. Hive:如何转换毫秒时间戳?
- 6. 在javascript中将时间戳转换为毫秒
- 7. 转换时间为毫秒?
- 8. 将时间戳转换为自世纪以来的毫秒数
- 9. 在毫秒中将毫秒转换为日期时间
- 10. 将毫秒转换为时间
- 11. 将毫秒转换为时间码
- 12. 将毫秒转换为日期/时间
- 13. SQL将时间转换为毫秒
- 14. 将时间变量转换为毫秒
- 15. Haskell将时间毫秒转换为UTCTime
- 16. 将给定时间转换为毫秒
- 17. 是否可以使用Python将时间戳转换为毫秒?
- 18. 使用PHP将毫秒数转换为javascript时间戳
- 19. 如何将模糊的时间戳转换以毫秒为Java日期
- 20. 在Python中将字符串时间戳转换为秒或毫秒
- 21. 如何将GMT时间转换为EPOCH时间戳以毫秒为单位?
- 22. 将毫秒转换为毫秒
- 23. 将时间戳转换为纳秒
- 24. php将秒转换为时间戳
- 25. 从Python中的时代将人类可读时间戳转换为毫秒
- 26. 的Java VS C#毫秒时间戳代
- 27. 在AWK中将unix时间戳转换为hh:mm:ss:SSS(其中SSS为毫秒)
- 28. 如何使用Scala将毫秒中的字符串列转换为Spark 2.1中的毫秒时间戳?
- 29. 将日期时间字符串转换为毫秒UNIX时间戳
- 30. 接收UNIX时间戳和转换时间,以毫秒WP7
+1 - 是的....但是,请注意,根据上下文,这使得测试非常困难(它将您的代码链接到机器/虚拟机的时间)。这是我更喜欢的原因之一[JodaTime](http://www.joda.org/joda-time/) - 它提供了[实用程序类](http://www.joda.org/joda-time/) apidocs/org/joda/time/DateTimeUtils.html),它允许你停止/抵消/不管时钟。 –
@ Clockwork-Muse个人我会做没有Java插入当前时间MySql。只需使用NOW()函数或CURRENT_TIMESTAMP MySql表达式(如果java程序的时区当然不重要)。 – Nailgun