Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/343.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 如何使用时间戳构造函数_Java_Timestamp_Deprecated_Default Constructor - Fatal编程技术网

Java 如何使用时间戳构造函数

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

我想在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/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());