Java 如何使用时间戳构造函数
我想在Java中为Timestamp类使用默认构造函数,但Eclipse指出它已被弃用。这是构造器:Java 如何使用时间戳构造函数,java,timestamp,deprecated,default-constructor,Java,Timestamp,Deprecated,Default Constructor,我想在Java中为Timestamp类使用默认构造函数,但Eclipse指出它已被弃用。这是构造器: Timestamp myDate=新的时间戳(2014,3,24,0,0,0,0) Eclipse建议使用时间戳(长时间)默认构造函数,但我不知道如何使用它。如中所述,您可以使用DateFormat类解析它: DateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy"); Date date = dateFormat.parse("23/0
Timestamp myDate=新的时间戳(2014,3,24,0,0,0,0)代码>
Eclipse建议使用时间戳(长时间)
默认构造函数,但我不知道如何使用它。如中所述,您可以使用DateFormat类解析它:
DateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy");
Date date = dateFormat.parse("23/09/2007");
long time = date.getTime();
new Timestamp(time);
创建一个java.util.Date
实例(不要与java.sql.Date
混淆),并将其时间(以毫秒为单位)作为参数传递给时间戳
。下面是一个例子:
Timestamp now = new Timestamp(new java.util.Date().getTime());
还有其他方法可以创建java.util.Date
对象实例:
- 使用
日历
:
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.HOUR, 0);
calendar.set(Calendar.MINUTE, 0);
calendar.set(Calendar.SECOND, 0);
calendar.set(Calendar.MILLISECOND, 0);
Date today = calendar.getTime();
Timestamp now = new Timestamp(today.getTime());
- 使用
DateFormat
或其子类SimpleDataFormat
SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd");
Date date = sdf.parse("2014/3/24");
Timestamp today = new Timestamp(date.getTime());
您可以使用GregorianCalendar类
GregorianCalendar cal = new GregorianCalendar(int year, int month, int dayOfMonth, int hourOfDay, int minute, int second);
Timestamp ts = new Timestamp(cal.getTimeInMillis());
如果您有以下格式的字符串,则还可以执行以下操作:
Timestamp ts = Timestamp.valueOf("2014-01-01 00:00:00");
下一个呢
使用(在JavaSE8中介绍):
为特定日期设置日历,然后在时间戳的构造函数中使用以毫秒为单位的时间:
new Timestamp(new GregorianCalendar(2014, 3, 24).getTimeInMillis());
当前时间的时间戳(System.currentTimeMillis())。使用Calendar.getInstance
而不是直接使用GregorianCalendar
。我有int
变量myYear
,myMonth
和myDay
。我如何在这里使用它们:Timestamp ts=Timestamp.valueOf(“myYear myMonth myDay 00:00:00”)
@robysottini您还可以在日历
属性中设置变量,并生成日期
对象。。。
java.sql.Timestamp ts = java.sql.Timestamp.valueOf(
java.time.LocalDate.of(myYear, myMonth, myDay).atStartOfDay()
);
new Timestamp(new GregorianCalendar(2014, 3, 24).getTimeInMillis());