Domanda

I want to use the default constructor for the Timestamp class in Java but Eclipse indicates that it is deprecated. This is the constructor:

Timestamp myDate = new Timestamp(2014, 3, 24, 0, 0, 0 ,0);

Eclipse recommends using Timestamp(long time) default constructor but I don't know how to use it.

È stato utile?

Soluzione

What about the next method?

int myYear = 2014;
int myMonth = 3;
int myDay = 24;
Timestamp ts = Timestamp.valueOf(String.format("%04d-%02d-%02d 00:00:00", 
                                                myYear, myMonth, myDay));

Using JSR 310: Date and Time API (introduced in the Java SE 8 release):

java.sql.Timestamp ts = java.sql.Timestamp.valueOf(
        java.time.LocalDate.of(myYear, myMonth, myDay).atStartOfDay()
);

Altri suggerimenti

Create a java.util.Date instance (not to be confused with java.sql.Date) and pass its time in milliseconds as argument to the Timestamp. Here's an example:

Timestamp now = new Timestamp(new java.util.Date().getTime());

There are other ways to create a java.util.Date object instance:

  • Using Calendar:

    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());
    
  • Using DateFormat or it's child class SimpleDateFormat.

    SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd");
    Date date = sdf.parse("2014/3/24");
    Timestamp today = new Timestamp(date.getTime());
    

As explained in this answer, you can parse it using the DateFormat class:

DateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy");
Date date = dateFormat.parse("23/09/2007");
long time = date.getTime();
new Timestamp(time);

Set up Calendar for specific date, then get time in millisecond are use it in constructor of Timestamp:

new Timestamp(new GregorianCalendar(2014, 3, 24).getTimeInMillis());

You can use the GregorianCalendar class

GregorianCalendar cal = new GregorianCalendar(int year, int month, int dayOfMonth, int hourOfDay, int minute, int second);
Timestamp ts = new Timestamp(cal.getTimeInMillis());

If you have a string in the below format, then you can also do:

Timestamp ts = Timestamp.valueOf("2014-01-01 00:00:00");
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top