Can't write time to database, only date. time gets ignored - java

I am trying to insert date and time but only the date goes through. when I check the database the time is always 00:00
public void suspendPart(String partId, String startDate,
String reasonCode, String endDate) throws DAOException {
System.out.println("original date: "+startDate); //output: original date: 04/01/2013 08:42
SimpleDateFormat format = new SimpleDateFormat("dd/MM/yyyy HH:mm");
Map<String, Object> params = new HashMap<String, Object>();
params.put("p_id", Integer.parseInt(partId));
Date dateTest = DAOUtils.parseDate(startDate, format);
System.out.println("date after format " +dateTest); // output: date after format Fri Jan 04 08:42:00 GMT 2013
params.put("p_start_date", dateTest);
parts_package_add_part.execute(params);
}
I managed to make it work once but I don't know how. by the time I checked the database and saw a row with proper time, I had already messed with the code so it was lost.
Can anyone see what I'm doing wrong?
Edit: sp declaration
parts_package_add_part = SpringStoredProcedure
.getStoredProcedureCompiled(getJdbcTemplate(), false,
"parts_package.add_part",
new SqlParameter("part_id", OracleTypes.NUMBER),
new SqlParameter("p_start_date", OracleTypes.DATE));
Edit: I can't change the database. well not easily at least. I would need to get PLSQL developer to do it and that will take days

I recently had a simular problem. My solution was to use TIMESTAMP as oracle data type in the database table and the java.sql.Timestamp class in java. This matched fine...

Using Timestamp could help. What is the datatype used to store your date in db? May be it is a Date type. If you convert that to Timestame/DateTime it could help.

Hi try using timestamp datatype in your database table and also from your java code use java.sql.Timestamp it will store data and time both for you
Thanks

Related

How to store time in MySQL

I have an html page having a form with input type="time".
This time is in 12 hr format by default.
The user will select the time and it should get stored in the MYSQL database.
In my database, I have created a table with the field called "bookingTime" and its datatype is TIME.
I am trying to write the java code to store the time in the database.
The problem is, when I select the time (for Ex. 03.30 PM) on the HTML page, it is being received in the backend as "1970-01-01T20:30:00.000Z".
I am not able to parse this and store the actual time(which is 15:30:00) in the MYSQL database.
Can someone provide me the java code to do this?
You can use a Calendar variable, so you can create a new Calendar and set the time.
After that, use a PreparedStatement to set the time as String, using SimpleDateFormat("HH:mm:ss")
Calendar myCalendar = Calendar.getInstance();
myCalendar.set(Calendar.HOUR, hour);
myCalendar.set(Calendar.MINUTE, minute);
myCalendar.set(Calendar.SECOND, second);
SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss" );
String time = sdf.format( myCalendar.getTime() );
...
ps.setString("myTimeField", time);
Here I am using your String "1970-01-01T20:30:00.000Z", but it should be replaced with your expected content from that form
DateFormat formatFromHtml = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");
DateFormat formatterToMySQL = new SimpleDateFormat("H:mm:ss");
Date result = formatFromHtml.parse("1970-01-01T20:30:00.000Z");
String validForTimeInMysql = formatterToMySQL.format(result);
After that, in validForTimeInMysql you get a String that can be added to MySQL

Java convert unix timestamp to wrong time

I have unix timestammp stored in mysql. I am converting it into time. It displays wrong time.
Here is code:
Date date = new Date((long)timestamp*1000);
SimpleDateFormat sdf = new SimpleDateFormat("h:mm a");
sdf.setTimeZone(TimeZone.getTimeZone("GMT+5:30"));
timeString = sdf.format(date);
System.out.println(timeString);`
timestamp is variable which contains unix timestamp.
Ex: for timestamp=1417437428505 it should show 6:07 PM and showing 12:31 AM
What is solution for it?
You're multiplying a timestamp which is already in milliseconds since the Unix epoch by 1000. You just want:
Date date = new Date(timestamp);
If you look at all of the date, not just the time, you'll see it's currently in 46886!
Are You sure that need multiplied by 1000? I tried pass without multiplying Date date = new Date(timestamp); and it printed 6:07 PM
Remove multiply with 1000 in
Date date = new Date((long)timestamp*1000);
than it works.

String -> java.util.Date -> java.sql.Date (with time stamp)

Here is my problem:
I have a user input a date like: 2012-12-24 (string)
I concatenate a time to that string, and convert to java.util.Date
My code looks like:
String tempstartdate = startdte; //startdte is the string value from a txtfield
tempstartdate += " 00:01:00";
String tempenddate = startdte;
tempenddate += " 23:59:59";
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
java.util.Date validstartdte = null;
java.util.Date validenddte = null;
validstartdte = df.parse(tempstartdate); //validstartdte is a util.Date (and works)
validenddte = df.parse(tempenddate);
My problem is, when I take that util.Date and want to make it an sql.Date:
java.sql.Date sqlstartDate = new java.sql.Date(validstartdte.getTime());
java.sql.Date sqlendDate = new java.sql.Date(validenddte.getTime());
It will not give me the timestamp I assigned, it will only return the date in the form yyyy-MM-dd (such as 2012-12-23).
WHY!? I'm so frustrated.
Note: I noticed that when I used breakpoints, I was able to expand sqlendDate and see there is a value in there called cdate that returns: 2012-12-12T23:59:59.000-0500
The database I'm using is PostgreSQL.
Please help! Much appreciated.
java.sql.Date doesn't have the time.
Use java.sql.Timestamp instead.
I might be very late to answer this question but I think it might be helpful.
As stated by 'Felipe Fonseca', I converted the util date to sql date as follows:
public static java.sql.Timestamp convertToSqlDateTime(Date utilDate){
return new java.sql.Timestamp(utilDate.getTime());
}
Normally, java.sql.Date only returns Date value and time will be discarded. So, in order to get time also, java.sql.TimeStamp must be used.
TimeStamp Constructs a Timestamp object using a milliseconds time value. The integral seconds are stored in the underlying date value; the fractional seconds are stored in the nanos field of the Timestamp object.
For this purpose, utilDate.getTime() is used to return the number of milliseconds since January 1, 1970, 00:00:00 GMT represented by this Date Object.
If we want only java.sql.Date, we can do:
public static java.sql.Date convertToSqlDate(Date utilDate){
return new java.sql.Date(utilDate.getTime());
}
I have completely given up on using Java's standard Date classes, for exactly the reasons you list.
I've been using Joda Time for a while now, and have found it a lot simpler.

Difference between two dates with different timezones

I'm trying to obtain the difference between two dates but i'm stuck at converting a string into a date.
My code is:
//create a date send it to the database as string
Date currentDate = new Date(); // date looks like: Sat Sep 01 10:20:14 EEST 2012
SaveToDB(currentDate.ToString());
At some point i;m trying to retrieve the date from the database:
String dateStringFromDb = GetDateFromDB(); //Sat Sep 01 10:20:14 EEST 2012
Date currentDate = new Date();
//now i'm trying to covnert the dateStringFromDb into a Date, this throws an exception
Date dbDate = DateFormat.getInstance().parse(dateStringFromDb); //this throws exception
long difference = currentDate.getTime() - dbDate.getTime(); // does this give me the correct difference in GMT even if timezones for the two dates are different?
Can you please point me to the correct solution?
Unfortunately the date from the database is retrieved as a String and i can't change that to another type. So i need to convert that string into Date().
EDIT:
Exception is :
java.text.ParseException: Format.parseObject(String) failed
at java.text.Format.parseObject(Unknown Source)
at main.Program.main(Program.java:20)
I would suggest using Joda Time API for your data and time related operation in Java. Handling timezone and all related conversion nuances are pretty easy using this API.
You should specify a DateFormat to match the string format being received
Eg.
SimpleDateFormat fromUser = new SimpleDateFormat("dd/MM/yyyy");
SimpleDateFormat myFormat = new SimpleDateFormat("yyyy-MM-dd");
String reformattedStr = myFormat.format(fromUser.parse(inputString));
Once you have the both the dates in required format, then apply the date arithmetic operations
Other Format Specifiers for DateString can be found in
http://docs.oracle.com/javase/6/docs/api/java/text/SimpleDateFormat.html

Parsing a string to date gives 01/01/0001 00:00:00

String dateimput=request.getParameter("datepicker");
System.out.printl("datepicker:" +dateimput);
DateFormat df = new SimpleDateFormat("MM/dd/yyyy");
Date dt = null;
try
{
dt = df.parse(dateimput);
System.out.println("date imput is:" +dt);
} catch (ParseException e)
{
e.printStackTrace();
}
*datepicker:04/29/2010 (value I currently selected from datepicker).
*the field in database is typed date.
1-date imput is:Thu Apr 29 00:00:00 CEST 2010
and in database level it is inserted like that 01/01/0001 00:00:00
Your Java code will work fine.
04/29/2010 will give you a date object with the correct time/date set.
You said the problem is during the Database insert, so you should tell us the used database and post the code you are using for the insert.
Based on your comment to echox's answer. It looks like your problem might be not putting quotes around your date value in your insert statement.

Categories

Resources