Java/Servlet: get current sql.Date
42,546
Solution 1
Even a more compact solution ;)
java.sql.Date timeNow = new Date(Calendar.getInstance().getTimeInMillis());
Solution 2
There is one more simple solution for it. use this code to get current date using java.util.Date
java.util.Calendar cal = java.util.Calendar.getInstance();
java.util.Date utilDate = cal.getTime();
java.sql.Date sqlDate = new Date(utilDate.getTime());
Solution 3
If you want the time, you need a java.sql.Timestamp not a java.sql.Date, and a timestamp column in the database.
Author by
Artemij
Updated on April 10, 2020Comments
-
Artemij about 4 years
What I need to do is:
1) Get user's locale from request.
2) Create new sql.Date object with current date and time, based on user's locale
3) Write it in MySQL db, column type: TIMESTAMP
What I got is:
java.util.Locale locale = request.getLocale(); java.text.DateFormat dateFormat = java.text.DateFormat.getDateTimeInstance( java.text.DateFormat.LONG, java.text.DateFormat.LONG, locale ); java.util.Date date = new java.util.Date(); java.sql.Date sqlDate = new java.sql.Date( date.getTime() );
Date is OK, but have a problem with time - always 12:00:00 AM.
Any suggestions? Is there a more efficient way to do this?
-
Artemij about 15 yearsThank you for that important note. Can you suggest an example of elegant solution?
-
Ryan over 11 yearsA more compact solution is:
java.util.Calendar cal = java.util.Calendar.getInstance();
java.sql.Date timeNow = new Date(cal.getTimeInMillis());
-
Ivan Stoyanov over 8 yearsThank you. This is what I was looking for :)