Mapping Date and Time to MySQL - java

I have created a table in MySQL as :
CREATE TABLE scheduled(sid INT,id INT,tweet VARCHAR(255),sdate DATE,
stime TIME,PRIMARY KEY(sid),FOREIGN KEY(id) REFERENCES usercred(id));
I receive both Date and Time from the HTML input field. Date received from the HTML field looks like :
4/30/2014
How can I map this in Java ? After receiving both Date and Time and after mapping them correctly , I will commit the transaction or will update the table/entry.

could use the parse() method in the SimpleDateFormat object:
SimpleDateFormat sdf = new SimpleDateFormat("M-dd-yyyy");
String dateInString = "4-30-1982"";
Date date = sdf.parse(dateInString);
System.out.println(date);

In JDBC-layer inside PreparedStatement or ResultSet you work with the mapping java.sql.Date (for SQL-DATE) and java.sql.Time (for SQL-TIME). Then you can wrap both types like:
java.sql.Date sqlDate = ...; // from ResultSet
DateFormat df = new SimpleDateFormat("MM/dd/yyyy"); // or M/d/yyyy
String htmlFormat = df.format(sqlDate);
And in reverse:
String htmlFormat = ...;
DateFormat df = new SimpleDateFormat("MM/dd/yyyy"); // or M/d/yyyy
java.util.Date d = df.parse(htmlFormat);
java.sql.Date sqlDate = new java.sql.Date(d.getTime());
// use result in PreparedStatement for INSERT or UPDATE
Attention: Both approaches use the standard timezone of the server where this code is running. In case of doubt you should probably set the timezone UTC. Similar code for the TIME-part.

Related

Insert Date in string format into a database having field type of Date

I am having a date in the following format as string.
String from_date = "2016-09-09";
I need to insert into into a database having date type field using PreparedStatement. I have done it in the following way.
DateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
Date fd = formatter.parse(from_date);
select1.setDate(1, fd);
But it is showing the error as
The method setDate(int.java.sql.Date) in the type PreparedStatement is not applicable to the arguments(int,java.util.Date)
You need to use a java.sql.Date when inserting in database. Try the following :
DateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
Date fd = formatter.parse(from_date);
java.sql.Date sqlDate = new java.sql.Date(fd.getTime());
select1.setDate(1, sqlDate);
Answered here: Type mismatch: cannot convert from java.util.Date to java.sql.Date
You are trying to use a method that accepts java.sql.Date instead of java.util.Date
Welcome to programming, mind the details
Using java.sql.Date
java.util.Date
Suppose you have a variable endDate of type java.util.Date, you make the conversion thus:
select1.setDate(1, new java.sql.Date(endDate.getTime());

Store date in SQLite

There is a lot of discussion here, but what I have tried isn't working. Till now in my tables I store the dates as a string, but I assume this isn't the right way... So I created a table:
CREATE TABLE "TRANSACTIONS" (
"date" DATETIME,
...
}
I want to store the date like 2016-11-04 10:50, so I use:
String timeStamp = new SimpleDateFormat("yyyy-MM-dd HH:mm").format(Calendar.getInstance().getTime());
I use prepared Statements to insert records in DB and when I try to do this:
stm.setDate(1, timeStamp);
I get that String cannot be converted to Date. So I convert it to DATE
String timeStamp = new SimpleDateFormat("yyyy-MM-dd HH:mm").format(Calendar.getInstance().getTime());
DateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm");
Date datee = formatter.parse(timeStamp);
and then I get java.util.Date cannot be converted to java.sql.Date so I tried this:
String timeStamp = new SimpleDateFormat("yyyy-MM-dd HH:mm").format(Calendar.getInstance().getTime());
java.sql.Date sqlDate = java.sql.Date.valueOf(timeStamp);
which when I run it, I get java.lang.IllegalArgumentException
java.sql.Date represents a date, not a date and time.
You are getting this error because you are passing "yyyy-MM-dd HH:mm" and throws java.lang.IllegalArgumentException
String d1 = "2016-10-11";
java.sql.Date d = null ;
d.valueOf(date1);
System.out.println(d.valueOf(date1));
`
This will run without any exception.
For your required format you should use java.sql.Timestamp
String date1 = "2016-10-11 10:45";
SimpleDateFormat sm = new SimpleDateFormat("yyyy-MM-dd HH:mm");
java.util.Date d2 = sm.parse(date1);
Timestamp time = new Timestamp(d2.getTime());
System.out.println(time);
Output - 2016-10-11 10:45:00.0

Timestamp to String to DateTime issues

I tried to see questions about date convert issues between two database using java but didn't solve my problem.
Here is the current date to insert in my database with a DateTime format :
java.sql.Date SQLDateValue = new java.sql.Date(System.currentTimeMillis()) ;
preparedStatement.setDate(index, SQLDateValue);
And here is the Timestamp from an API named Vdoc, convert to String and i tried to convert it to java.sql.Date (DateTime) :
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
java.util.Date DateValue = (java.util.Date) this.getWorkflowInstance().getValue(this.ListeChamps[i][2]);
String StringDateValue = DateValue.toString();
java.sql.Date SQLDateValue = new java.sql.Date (sdf.parse(StringDateValue).getTime());
preparedStatement.setDate(index, SQLDateValue);
The second line return a field value containing a String but i need to use toString().
The following error message is :
Failed to convert the date and / or time from a string.
Both of my date parameters are java.sql.date, i don't understand.
If you have an idea of ​​what happens with this, it would be nice to help me.
Ezerah
Sorry for my bad english
Just construct the java.sql.Date from java.util.Date.
Call java.util.Date::getTime to extract the count of milliseconds from epoch. Pass that count to constructor of java.sql.Date.
In your case below should work.
java.util.Date DateValue = (java.util.Date) this.getWorkflowInstance().getValue(this.ListeChamps[i][2]);
java.sql.Date SQLDateValue = new java.sql.Date (DataValue.getTime());
preparedStatement.setDate(index, SQLDateValue);
try this:
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
java.util.Date DateValue = **sdf.parse(**this.getWorkflowInstance().getValue(this.ListeChamps[i][2])**)**;
String StringDateValue = DateValue.toString();
java.sql.Date SQLDateValue = new java.sql.Date (sdf.parse(StringDateValue).getTime());
preparedStatement.setDate(index, SQLDateValue);
You can't cast String to Date, you should parse it

Formatting timestamp in Java

I wish to produce a current timestamp in the format of yyyy-MM-dd HH:mm:ss. I have written up the following code, but it always gives me this format yyyy-MM-dd HH:mm:ss.x
How do you get rid of the .x part ?
DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String currentTime = df.format(new Date());
Timestamp timestamp = Timestamp.valueOf(currentTime);
I need to have a timestamp type for writing into mysql.
Probably you're looking at the String representation the Timestamp object gives in your database engine or its Java representation by printing it in the console using System.out.println or by another method. Note that which is really stored (in both Java side or in your database engine) is a number that represents the time since epoch (usually January 1st 1970) and the date you want/need to store.
You should not pay attention to the String format it is represented when you consume your Timestamp. This can be easily demostrated if you apply the same SimpleDateFormat to get a String representation of your timestamp object:
DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String currentTime = df.format(new Date());
Timestamp timestamp = Timestamp.valueOf(currentTime)
//will print without showing the .x part
String currentTimeFromTimestamp = df.format(currentTime);
Anyway, if you want the current time, just create the Timestamp directly from the result of new Date:
Timestamp timestamp = new Timestamp(new Date().getTime());
You can insert the timestamp as a String to the MySQL table. Your String representation in currentTime is sufficient.
The best way to write Timestamp or any data type in Java is to use PreparedStatement and an appropriate method
PreparedStatement ps = conn.prepareStatement("update t1 set c1=?");
ps.setTimestamp(1, new java.sql.Timestamp(new Date().getTime()));
ps.executeUpdate();

how to convert datetime to timestamp in java

forum member
I am having one problem with date time in java. Actually I am receiving the startdate in format 2012-02-27T01:10:10 and I want to insert the received date to my database having datetime datatype.
Actually I tried to convert the startdate received to datetime by below code
String sDate = jsonObject.get("StartDate").toString();
String eDate = jsonObject.get("EndDate").toString();
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
Date startD = sdf.format(sDate);
Date endD = sdf.format(eDate);
but with the above code only date gets added to my database like 2012-02-27 00:00:00
I want to add the time also to my database but when I change the SimpleDateFormat to SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); nothing works.
please suggest me some solution I can apply so my time also gets added to database. I am using Hibernate JPA as my persistence layer.
SimpleDateFormat's format() method doesn't return a Date type.
try this:
Date startDate = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss").parse(sDate);
Try this,
yyyy-MM-dd'T'HH:mm:ss
String sDate = jsonObject.get("StartDate").toString();
String eDate = jsonObject.get("EndDate").toString();
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
Date startD = sdf.format(sDate);
Timestamp startTime = new Timestamp(startD.getTime());
Date endD = sdf.format(eDate);
Timestamp endTime = new Timestamp(endD.getTime());
Of course only the date is parsed, since the pattern you provided to the SimpleDateFormat constructor only contains the date part! Add the time part to it and it will parse the time too just fine.
you can try like this....
DateFormat format = new SimpleDateFormat("MMddyyHHmmss");
Date date = format.parse("022310141505");

Categories

Resources