How can I create a Timestamp with the date 23/09/2007?
views:
1146answers:
5
+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
2009-06-10 11:19:54
+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
2009-06-10 11:23:08
+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
2009-06-10 11:26:30
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
2009-06-10 13:31:56
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
2009-06-10 13:55:02
+1
A:
What about this?
Timestamp timestamp = Timestamp.valueOf("2007-09-23 10:10:10.0");
pigouina
2009-06-10 11:38:26
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
2009-06-10 11:41:33
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
2009-06-10 13:29:23