views:

1146

answers:

5

How can I create a Timestamp with the date 23/09/2007?

+11  A: 

By Timestamp, I presume you mean java.sql.Timestamp. You will notice that this class has a constructor that accepts a long argument. You can parse this 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);
Adam Paynter
+2  A: 

According to the API the constructor which would accept year, month, and so on is deprecated. Instead you should use the Constructor which accepts a long. You could use a Calendar implementation to construct the date you want and access the time-representation as a long, for example with the getTimeInMillis method.

Philipp
+5  A: 

What do you mean timestamp? If you mean milliseconds since the Unix epoch:

GregorianCalendar cal = new GregorianCalendar(2007, 9 - 1, 23);
long millis = cal.getTimeInMillis();

If you want an actual java.sql.Timestamp object:

Timestamp ts = new Timestamp(millis);
Matthew Flaschen
WRONG and won't compile! Compile error: 09 is an octal number, but 9 is out of range for octals. Logic error: the month is 0-based, you will get OCTOBER 23th of 2007
Carlos Heuberger
I can't get a logic error if it doesn't compile. :) Seriously, good catches, Carlos. The octal I caught before but pasted wrong anyway. :(
Matthew Flaschen
+1  A: 

What about this?

Timestamp timestamp = Timestamp.valueOf("2007-09-23 10:10:10.0");

pigouina
Yes, that works.
Matthew Flaschen
A: 

You could also do the following:

// untested
Calendar cal = GregorianCalendar.getInstance();
cal.set(Calendar.DAY_OF_MONTH, 23);// I might have the wrong Calendar constant...
cal.set(Calendar.MONTH, 8);// -1 as month is zero-based
cal.set(Calendar.YEAR, 2009);
Timestamp tstamp = new Timestamp(cal.getTimeInMillis());
atc
WRONG: try a System.out.println of the result! You'll get something like: "2009-10-23 15:26:56.171" Month is 0-based so 9 is October!
Carlos Heuberger
I knew one of those constants was zero-based, thanks.Post updated.
atc
Oh, and I did put 'untested' :)
atc