Comparing to get seconds difference between java and mysql datetime - java

I read a mysql date time field into one string e.g.
String arriveTime = rs1.getString("arriveTime");
Next step I try to get the current date and time using java to be similar format like the one I got from mysql.
DateFormat outDf=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String currentDateTimer=null;
Date date = Calendar.getInstance().getTime();
currentDateTimer=outDf.format(date);
How can I minus the currentDateTime and arriveTime to get the net results in seconds. I would prefer to do it purely via java

First, I would not read a MySQL date-time into a String. I would change this,
String arriveTime = rs1.getString("arriveTime");
to
java.sql.Date arriveTime = rs1.getDate("arriveTime");
Then you can use basic subtraction to get the result in milliseconds, then divide by a thousand to get that in seconds - so
long diff = new java.util.Date().getTime() - arriveTime.getTime();
System.out.println(diff / 1000);

I read a mysql date time field into one string
If the column is varchar type it is ok you can read it using resultsetObject.getString()
But if your column type is Date then is it always recommended to get the value using resultset.getDate()
Mysql stores date in the format yyyy-MM-dd
I try to get the current date and time using java to be similar format
like the one I got from mysql.
When you do resultset.getDate() it will give you the java.sql.Date in format yyyy-MM-dd

Related

How to convert date in string with or without time into DATE

I have a date in string format like "2017-11-16" or "2017-11-16 12:59:11.243". I have to convert it to Date.
Below is my code:
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.sss");
Date createdOn = formatter.parse(date);
It works fine when the date is "2017-11-16 12:59:11.243". But not able to format with "2017-11-16" date.
String date is coming from URL, so it could be either with time or without time. How can I convert it into Date in spite of the fact what type of date is coming from URL?
Actually, I have to find row from the database based on the date. In the database, the date is storing in the format like 2017-11-16 12:59:11.243. But If from URL 2017-11-16 is coming then it should find according to this date.
You can modify the pars based on the presence of time,
if(dateOrDataTime.contains(":")){
//Use parser with date-time. & fetch with equal
}else{
//Use parser for date only. & fetch using date(date_time)
}

Joda dateTime parser is adding milliseconds unnecessarily

I have the time in milliseconds which I need to convert to 2009-01-31T06:34:45Z using Joda library. I have written the below program but the date parser is adding milliseconds by default.
DateTimeFormatter fmt = DateTimeFormat.forPattern("yyyy-MM-dd'T'HH:mm:ss'Z'");
DateTime dateTime = new DateTime(System.currentTimeMillis());
String str = fmt.print(dateTime);
System.out.println("Date as string - " + str);
dateTime = fmt.parseDateTime(str);
System.out.println("Date as Joda dataTime - " + dateTime);
Following is the output:
Date as string - 2007-03-24T23:03:44Z
Date as Joda dataTime - 2007-03-24T23:03:44.000+05:30
.000+05:30 is getting added to the dateTime object. The print method print the dateTime in correct format, but the parse method adds milliseconds and timezone unnecessarily. Please let me know the mistake in the program.
.000+05:30 is getting added to the dateTime object
No, it's included in the result of dateTime.toString(), that's all. A DateTime value doesn't have any concept of its own format - it's just a date/time/calendar/zone. If you want to convert a DateTime value to a specific format, you need to go through the formatter again - which you clearly know how to do, as you're already doing it in your code.
It's very important to distinguish between "the data in the object" and "the text representation you want". A DateTime is always stored with a precision of milliseconds, regardless of what it happened to be parsed from.

How to convert a date format to mysql date format?

I have bunch of dates in a format like Jan. 14,2014,Apr. 20,2014,Aug. 14,2014 etc,. which are extracted from a set of PDF documents.
My Problem
I added the above dates to a mysql column with Column Datatype as Date using java (by PreparedStatement).
....
st.SetDate(3,"Jan. 14,2014");
....
I added the datas using ExecuteQuery.
But when program executes an error message returned by MySql stating that the date formats are incompatible with MySql column type) Date..
My Question
How to convert this above mentioned date formats into mysql compatible Date formats ?
By your current posted code:
st.SetDate(3,"Jan. 14,2014");
This does not even compile. You could try getting a new Date object from a String (since this is what you're trying to accomplish), so use a SimpleDateFormat for this:
SimpleDateFormat sdf = new SimpleDateFormat("MMM. dd,yyyy");
Date date = sdf.parse("Jan. 14,2014");
st.setDate(3, new java.sql.Date(date.getTime()));
//rest of your code...
Similar to this, you can parse time or date and time into a java.util.Date using SimpleDateFormat and then convert it to the respective class java.sql.Time and java.sql.Timestamp using date.getTime().
Also note that you can p̶a̶s̶s̶ retrieve a java.util.Date object reference to PreparedStatement#getDate (and getTime and getTimestamp) since java.sql.Date, java.sql.Time and java.sql.Timestamp extend from java.util.Date. For more info, please refer here: Date vs TimeStamp vs calendar?
Assuming the column type supports a Date value, you could use a SimpleDateFormat to parse the String values to a java.util.Date and create a java.sql.Date which can be applied to the setDate method...
SimpleDateFormat sdf = new SimpleDateFormat("MMM. dd,yyyy");
Date date = sdf.parse("Jan. 14,2014");
java.sql.Date sqlDate = new java.sql.Date(date.getTime());
Check it SimpleDateFormat for more details
One possible solution is to use the String datatype instead of date in your table.
Use SimpleDateFormat to get the string representation of the date to a Date Object.
This date object can then be used to feed the set date method of the prepared statement.
SimpleDateFormat sdf = new SimpleDateFormat(....)
java.util.Date date = sdf.parse(....);
preparedStmt.setDate(...., date);
first convert the java.util.Date to java.sql.Date then try to set the Java.sql.Date
you can use this logic to convert
If your date is String then first convert it into Java.util.Date type either by using the SimpleDateFormat or DateFormat
If u want to use a DateFormat you can use it also:
But this changes the expected date format depending on the locale settings of the machine it's running on.
If you have a specific date format, you can use SimpleDateFormat:
Date d = new SimpleDateFormat("MMM. dd,yyyy").parse("Jan. 14,2014");
java.sql.Date sqlDate = new java.sql.Date(d.getTime());
I don't really think this all java stuff is necessary. You can simply use this very easy sql process to insert date: NOW() in mysql query like INSERT INTO table_name(c1,c2,datecolumn) VALUES('value1','value2',NOW()); It is much simplier I think :D

MySql DATETIME to java.util.Calendar

I managed in JAVA to store a calendar into a mysql DATETIME field
To fetch this value
entry.date = Calendar.getInstance(TimeZone.getTimeZone("UT"));
entry.date.setTime(rs.getDate(DBBLogEntries.entDate));
Where the entry.date is a java.util.Calendar
In the database the value is this: '2012-07-07 07:18:46'
I store all date values in a unique timezone in the db. ready to make all the extra work required to add or substract hours depending on the country from wich the request is comming.
The problem is that it brings the date but doesn't seem to brinng me the time.
Any sugestion please?
Thanks in advance.
Probably because Java has a different date format than mysql format(YYYY-MM-DD HH:MM:SS)
Visit the link :
http://www.coderanch.com/t/304851/JDBC/java/Java-date-MySQL-date-conversion
You may use SimpleDateFormat as follows.
java.util.Date dt = new java.util.Date();
java.text.SimpleDateFormat sdf =
new java.text.SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String dateTime = sdf.format(dt);
You should read a timestamp from the ResultSet object.
java.sql.Timestamp ts = rs.getTimestamp( DBBLogEntries.entDate );
Which returns a Timestamp instance that includes date and time.
don't use Java.util.Date ,use the Java.sql.Date.
Are you using the MySql DATE type? This does not preserve the time component.
http://dev.mysql.com/doc/refman/5.5/en/datetime.html
Alternatively how are you retrieving the date from the db?

Update/ Retrieve /Inserting date field

I am having difficulties while updating a date field into the Database. The field type in the DB is Date/Time.
Now, I am trying to update the field name "R_Date".
Currently, I am using the SQL Expression in my jsp"
UPDATE request SET request_date ='"+Request_Date+"'"; , But it is not accepting.
In the select statement I am using a normal select, I tried to use to_char or to_date, but it is not accepting the format of "DD-MMM-YYYY"
So, can you please help me to retrive/Update/Insert date field in the format of "DD-MMM-YYYY" the date field?
The normal practice to store a timestamp in the DB (thus, java.util.Date in Java side and java.sql.Timestamp in JDBC side) is to use PreparedStatement#setTimestamp().
Date requestDate = getItSomehow();
Timestamp timestamp = new Timestamp(requestDate.getTime());
preparedStatement = connection.prepareStatement("UPDATE request SET request_date = ?");
preparedStatement.setTimestamp(1, timestamp);
The normal practice to obtain a timestamp from the DB is to use ResultSet#getTimestamp().
Timestamp timestamp = resultSet.getTimestamp("request_date");
Date requestDate = timestamp; // You can just upcast.
To convert between java.util.Date and java.lang.String you normally use SimpleDateFormat:
// Convert from String to Date.
String requestDateAsString = "09-Aug-2010";
SimpleDateFormat sdf = new SimpleDateFormat("dd-MMM-yyyy", Locale.ENGLISH);
Date requestDate = sdf.parse(requestDateAsString);
// Convert from Date to String.
String anotherDateAsString = sdf.format(someDate);
See also:
PreparedStatement tutorial
How to avoid Java code in JSP file (!!!)
I think you should use MON instead of MMM.
Have you tried something like:
UPDATE request
SET request_date = to_date('" + Request_Date + "', 'DD-MON-YYYY')
Hope you realize that as your statement stands (if it worked), it would update every row in the request table (not sure if that's your intention or not but I thought I'd point it out).
You need to check what date format you are trying to insert, and try using to_date method with appropriate format.
Following is referenced from : http://infolab.stanford.edu/~ullman/fcdb/oracle/or-time.html
Oracle's default format for DATE is "DD-MON-YY".
If you want to retrieve date in particular format you need to use :
TO_CHAR(<date>, '<format>')
Similarly if you need to insert/update date with input of date other than in standard format, you need to use :
TO_DATE(<string>, '<format>')
where the <format> string can be formed from over 40 options. Some of the more popular ones include:
MM Numeric month (e.g., 07)
MON Abbreviated month name (e.g., JUL)
MONTH Full month name (e.g., JULY)
DD Day of month (e.g., 24)
DY Abbreviated name of day (e.g., FRI)
YYYY 4-digit year (e.g., 1998)
YY Last 2 digits of the year (e.g., 98)
RR Like YY, but the two digits are ``rounded'' to a year in the range 1950 to 2049. Thus, 06 is considered 2006 instead of 1906
AM (or PM) Meridian indicator
HH Hour of day (1-12)
HH24 Hour of day (0-23)
MI Minute (0-59)
SS Second (0-59)

Categories