String into java.sql.Date
Can anyone tell me how to convert a String (yyyy-mm-dd) into a java.sql.Date format? Also I need to test to see if the Date of birth (entered in the format above) is >= 18.
Can I do this in an SQL query?
Thanks
Marika Ludmann
Can anyone tell me how to convert a String
(yyyy-mm-dd) into a java.sql.Date format? Also I need
to test to see if the Date of birth (entered in the
format above) is >= 18.
Can I do this in an SQL query?
Thanks
Marika LudmannTry this:
String dateStr = "2003-04-29";
SimpleDateFormat formater = new SimpleDateFormat("yyyy-MM-dd");
Date result = formater.parse(dateStr);Don't forget to add the
import java.text.SimpleDateFormat;
Similar Messages
-
Convert string into java.sql.Date
Hi,
I want to convert a date in string form into java.sql.Date to persist into the database column with Date as its datatype in Oracle. I'm trying as follows:
import java.sql.Date;
import java.text.ParseException;
import java.text.SimpleDateFormat;
public class DateTest
public static void main(String[] args)
String strDate = "2002-07-16 14:45:01";
System.out.println("strDate = "+strDate);
Date aDate = null;
try
if(strDate != null && !strDate.trim().equals(""))
SimpleDateFormat aSDF = new SimpleDateFormat();
aSDF.applyPattern("yyyy-MM-dd hh:mm:ss");
java.util.Date utilDate = aSDF.parse(strDate);
System.out.println("utildate = "+utilDate);
aDate = new Date(utilDate.getTime());
aDate.setTime(utilDate.getTime());
System.out.println("aDate = "+aDate);
catch (ParseException e)
System.out.println("Unable to parse the date - "+strDate);
catch (Exception ex)
ex.printStackTrace();
System.out.println("Caught Exception :"+ex.getMessage());
It gives the output as :
strDate = 2002-07-16 14:45:01
utildate = Tue Jul 16 14:45:01 IST 2002
aDate = 2002-07-16
If I put this value into the database table, I can see only the date. Time part is missing. Is this the problem with java.sql.Date or Oracle datatype Date? Please help me asap.
Thanks in advance.
Regards,
Rajapriya.R.If I put this value into the database table, I can
see only the date. Time part is missing. Is this the
problem with java.sql.Date or Oracle datatype Date?This is not a problem, this is the defined behaviour of the Date type. RTFAPI and have a look at Timestamp, while you're at it. -
Convert a String to java.sql.Date Format
Hi,
I am having a String of containing date in the format 'dd/mm/yyyy' OR 'dd-MMM-YYYY' OR 'mm-dd-yyyy' format. I need to convert the string to java.sql.Date object so that I can perform a query the database for the date field. Can any one suggest me with the code please.
Regards,
Smithaimport java.text.SimpleDateFormat;
import java.text.ParseException;
import java.util.Date;
public class TestDateFormat
public static void main(String args[])
SimpleDateFormat sdf = new SimpleDateFormat("dd-MM-yyyy");
System.out.println(sdf.isLenient());
try
Date d1 = sdf.parse("07-11-2001");
System.out.println(d1);
Date d2 = sdf.parse("07:11:2001");
System.out.println(d2);
catch(ParseException e)
System.out.println("Error format, " + e);
See class DateFormat and SimpleDateFormat for detail. -
Needed help regarding converting string to java.sql.Date format
I have a a function which returns a calendar object. The date must be inserted to Oracle DB using java.sql.Date format.
So i have converted the Calendar object to java.sql.Date format using the following code
java.sql.Date publicationDate = new java.sql.Date(book.getPublicationDate().getTime().getTime());But while getting inserted into the DB it was in mm/dd/yyyy format whereas i wanted dd/mm/yyyy format
Can any body please help out how to store the date in dd/mm/yyyy format ?Can u please explain this a bit
This is my code
public int addBook(List<Book> BookList) throws SQLException, ParseException{
System.out.println("Hi there");
Book book = new Book();
BookDB bookDb = new BookDB();
//listLength = BookList.length;
String bookId = null;
try{
DriverManager.registerDriver(new oracle.jdbc.driver.OracleDriver());
con = DriverManager.getConnection("jdbc:oracle:thin:@10.123.79.195:1521:findb01","e115314", "e115314");
addBook = con.prepareStatement("insert into ABC_Book values(?,?,?,?,?,?,?)");
Iterator<Book> iterator = BookList.iterator();
while(iterator.hasNext()){
book = (Book)iterator.next();
System.out.println(book.getBookId());
addBook.setString(1,book.getBookId());
addBook.setString(2,book.getTitle());
addBook.setString(3,book.getAuthor());
addBook.setString(4,book.getPublisher());
System.out.println(book.getPublicationDate());
System.out.println("Before Date");
System.out.println("book.getPublicationDate().getTime()"+book.getPublicationDate().getTime());
java.sql.Date publicationDate = new java.sql.Date(book.getPublicationDate().getTime().getTime());
SimpleDateFormat formatter = new SimpleDateFormat("dd/mm/yyyy");
dateString = formatter.format(publicationDate);
System.out.println("Today is"+dateString);
java.sql.Date date = (java.sql.Date)formatter.parse(dateString);
System.out.println("date"+date);
//java.sql.Date publicationDate = (Date)book.getPublicationDate().getTime();
//System.out.println("Value of date is"+publicationDate);
System.out.println("After Date");
addBook.setDate(5,publicationDate);
addBook.setString(6,book.getCountry());
addBook.setString(7,book.getLanguage());
rs = addBook.executeQuery();
//con.commit();
rowCount = rowCount + rs.getRow();
return rowCount;
catch(SQLException se){
se.printStackTrace();
finally{
con.close();
System.out.println("After adding ");
return 0;
} -
Trying to convert String to java.sql.Date
I need to convert a String (in the format "yyyy-mm-dd") to java.sql.Date
It was suggested I use the following,
SimpleDateFormat formater = new SimpleDateFormat("yyyy-mm-dd");
Date result = formater.parse(dbirth.getText());
However, It seem to produce a java.util.Date
Error: found java.util.Date
Required : java.sql.Date
Can anyone help?
Thanks, MarikaI need to convert a String (in the format
"yyyy-mm-dd") to java.sql.Date
It was suggested I use the following,
SimpleDateFormat formater = new
SimpleDateFormat("yyyy-mm-dd");
Date result = formater.parse(dbirth.getText());
However, It seem to produce a java.util.Date
Error: found java.util.Date
Required : java.sql.Date
Can anyone help?
Thanks, Marika SimpleDateFormat formater = new SimpleDateFormat("yyyy-mm-dd");
java.util.Date parsedDate = formater.parse(dbirth.getText());
java.sql.Date result = new java.sql.Date(parsedDate.getTime()); -
Convert a string to JAva.sql.date..
I am having a string with the value as follows..
String fval="03-10-2001"..
I am using this value in a rs.updateDate method where I need to convert it to a different format as
2001-10-03...can anybody give me the syntax..You should hold dates as Date instances. But if you want to convert between Strings and Dates then you should use a DateFormat:
String originalDateString = "31-10-2001";
// Convert the original string to a date
DateFormat originalDateFormat = new SimpleDateFormat("dd-MM-yyyy");
Date date = originalDateFormat.parse(originalDateString);
// Get a representation of the date in the new format
DateFormat newDateFormat = new SimpleDateFormat("yyyy-MM-dd");
String newDateString = newDateFormat.format(date);(Excuse the quirky formatting that the Java code filter applies!)
Hope this helps. -
How do I create a Dynamic java.sql.Date ArrayList or Collection?
I Have a MySQL table with a Datetime field with many values inserted.
I want to know which is the Best way to capture all the Inserted DB values inside a Dynamic Array.
I get errors that state that I should use Matching data-types, and plus I don't know how to create or fill a Dynamic Date ArrayList/Collection.
Please Help, I need this urgently...package pruebadedates;
import java.sql.*;
* @author J?s?
public class ClaseDeDates {
/** Creates a new instance of ClaseDeDates */
* @param args the command line arguments
public static void main(String[] args) {
java.sql.Date aDate[] = null;
Connection con = null;
Statement stmt = null;
ResultSet rs = null;
try{
Class.forName("com.mysql.jdbc.Driver").newInstance();
con = DriverManager.getConnection("jdbc:mysql://localhost/pruebafechas", "root", "picardias");
if(!con.isClosed()){
stmt = con.createStatement();
stmt.executeQuery ("SELECT dates FROM datestable");
rs = stmt.getResultSet();
while (rs.next())
aDate[] = rs.getDate("dates");
catch(Exception e)
System.out.println(e);
//System.out.println(aDate);
}Hi, There is my code and the errors that I get are:
found : java.sql.Date
required: java.sql.Date[]
aDate = rs.getDate("dates");
Actually I have No idea as How to get a Result set into an ArrayList or Collection. Please tell me how to do this Dynamically. I have like 25 records in that Database table, but they will grow, so I would really appreciate to know the code to do this. I suspect my problem is in the bolded part of my code.
Thank you very much Sir. -
Hi all,
How to change a date value from "java.util.Date" to "java.sql.Date"?
I m still confusing what's the difference between them.....
thanks
Regards,
KinThanks
but my sql statement can only accept the format (yyyy-MM-dd)
such as "select * from xx where somedate = '2004-12-31'
but when i show it to screen, i want to show it as dd-MM-yyyy
I m using the following to change the jave.util.Date to str and vice versa. But it cannot shows the dd-MM-yyyy. I tried to change the format from yyyy-MM-dd to dd-MM-yyyy, it shows the wrong date in my application.
public String date2str(java.util.Date thisdate) {
if (thisdate != null) {
java.sql.Date thissDate = new java.sql.Date(thisdate.getTime());
return date2str(thissDate);
} else {
return "";
public String date2str(java.sql.Date thisdate) {
if (thisdate != null) {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
return sdf.format(thisdate);
} else {
return "";
public java.util.Date str2date(String thisdate) {
String dateFormat = "yyyy-MM-dd"; // = 1998-12-31
java.util.Date returndate = null;
if (thisdate != null) {
SimpleDateFormat dateFormatter = new SimpleDateFormat(dateFormat);
try {
returndate = dateFormatter.parse(thisdate);
} catch (ParseException pe) {
System.out.println (pe.getMessage());
return returndate;
} -
JTextfield input Date convert to java.sql.Date
Hi. I have a textfield for users to input date in 'dd/mm/yyyy' format and I would like to format this input into java.sql.Date to be stored into a database. How should I go about doing that ?
I did the following:
SimpleDateFormat formatDate = new SimpleDateFormat("dd/mm/yyyy");
java.util.Date invoiceDate = formatDate.parse(jTextField3.getText());
java.sql.Date sqlDate = new java.sql.Date(invoiceDate.getTime());and when I input into jTextField3 the value '28/05/2008' , I found in my database '2008-01-28'. January and May is a few months off and is totally not what I wanted.Hi you did you code perfect, but you need to change the pattern for formatting the Date
dd - date
mm - minute
yyyy - year
here you are parsing month as minute, so the output may wrong..!
If you need to format properly
please use the below pattern
{color:#0000ff}SimpleDateFormat formatDate = new SimpleDateFormat("dd/MM/yyyy");{color} -
How to convert JAVA.SQL.DATE date in YYYY/MM/DD format into DD/MM/YYYY
i am using informix database which accepts date value in the form of DATE format......
the other part of my application takes date from the field in DD/MM/YYYY format...so i have to convert my java.sql.date in YYYY/MM/DD fromat into DD/MM/YYYY fromat of same type before inserting into db......
but using parse method in SimpleDateFormat class can get the result only in java.util.date format...
and also using format method can result only in string conversion........816399 wrote:
i am using informix database which accepts date value in the form of DATE format......Huh?
Maybe you mean Informix (fronted by JDBC) expects date values as java.sql.Date objects?
the other part of my application takes date from the field in DD/MM/YYYY format...
so i have to convert my java.sql.date in YYYY/MM/DD format into DD/MM/YYYY format of same type before inserting into db......I am not sure why you are talking about formats here.
There is no formatting inherent in a java.util.Date object
nor in a java.sql.Date object.
but using parse method in SimpleDateFormat class can get the result only in java.util.date format...
and also using format method can result only in string conversion........You can easily create a java.sql.Date object from a java.util.Date object.
String s = "31/12/2010";
java.util.Date ud = new java.text.SimpleDateFormat("dd/MM/yyyy").parse(s);
java.sql.Date sd = new java.sql.Date(ud.getTime());
ud = sd; // java.sql.Date extends java.util.Date so no conversion is needed -
Hi,
I am new to this Technology.
in my Project DataBase I have the date field as String in format yyyy-mm-dd. when I am trying to fetch this date through the front-end I need to see the date in dd/mm/yyyy format of type java.sql.Date Variable.
if you know, Pl help me.
Thanks in Advance,
Kamala.Then use a SimpleDateFormat object to parse it into a Date object, and also to format the Date the way you want to see it, rather than simply relying on the toString() implementation.
-
How to convert String date to java sql date
I have an html form for entering the Date on retreving that value in a java servlet i get it as a string i want to convert that date to SQL date format so that i could use setDate() method of the java.sql.Date class to update the date value in the database.
i used the following way but i need the code without using the deprecated ones.
String delDate = (String)p_Request.getParameter("deleteDate");
[b]java.util.Date utilDate = new java.util.Date(delDate);
java.sql.Date deleteDate = new java.sql.Date(utilDate.getTime());
custCode = (String)p_Request.getValue("custCode");
thanx in advance.Check out the later posts in http://forum.java.sun.com/thread.jspa?threadID=647681&messageID=3814745#3814745
-
Convert String to java UTC date then to sql date
Hi,
I am trying to convert string (MM/dd/yyyy format) to UTC date time and store in the database.
This is what I did:
String dateAsString = "10/01/2007";
SimpleDateFormat formatter = new SimpleDateFormat("MM/dd/yyyy");
formatter.setTimeZone(TimeZone.getTimeZone("GMT"));
formatter.setLenient(false);
java.util.date dateValue = formatter.parse(dateAsString, new ParsePosition(0));
dateValue will be Sun Sep 30 20:00:00 EDT 2007 in UTC.
Now I need to store this date and time to MS SQL database.
I used the following code:
java.sql.Date sqlDateValue = new java.sql.Date(parsedToDate.getTime());
But this code give only the date, not time 2007-09-30
Can anybody tell me how I can change this java date to sql date (or datetime?) so that I can get both date and time.
Thanks,
semajsemaj07 wrote:
Hi,
I am trying to convert string (MM/dd/yyyy format) to UTC date time and store in the database.
This is what I did:
String dateAsString = "10/01/2007";
SimpleDateFormat formatter = new SimpleDateFormat("MM/dd/yyyy");
formatter.setTimeZone(TimeZone.getTimeZone("GMT"));
formatter.setLenient(false);
java.util.date dateValue = formatter.parse(dateAsString, new ParsePosition(0));
dateValue will be Sun Sep 30 20:00:00 EDT 2007 in UTC.
Now I need to store this date and time to MS SQL database.
I used the following code:
java.sql.Date sqlDateValue = new java.sql.Date(parsedToDate.getTime());
But this code give only the date, not time 2007-09-30
Can anybody tell me how I can change this java date to sql date (or datetime?) so that I can get both date and time.
Thanks,
semajTake a look at java.sql.Timestamp:
http://java.sun.com/javase/6/docs/api/java/sql/Timestamp.html
Edited by: hungyee98 on Oct 17, 2007 8:57 AM -
Converting String to Date (java.sql.date)
Hi,
Kindly let me know how I can convert a string like
"20061102" (YYYYMMDD) to a Date type (java.sql.date) in web Dynpro.
Requirement is to set a DateType context Attribute with
the value contained in the String ("20061102" ).
Awaiting your kind responses..
Regards,
MaheshSimpleDateFormat yyyyMMdd_parser = new SimpleDateFormat(
"yyyyMMdd");
java.util.Date date=yyyyMMdd_parser.parse("20061102");
java.sql.Date slqDate=new java.sql.Date(date.getTime()); -
Problem Writing java.sql.Date to MS Access
I have a relatively simple application that is for my own use (not distributed on an enterprise-wide basis). As I don't have an IT staff, I'm using a rudimentary Java front-end (v1.3.1) and a Microsoft Access backend.
I seem to have trouble using INSERT/UPDATE statements with the MS Access Date/Time data type. Below is an example of code being used (id is defined as Text, amount is a Number and timestamp is Date/Time):
conn = DriverManager.getConnection("jdbc:odbc:markets", "", "");
conn.setAutoCommit(true);
String sql = "INSERT INTO temp (id, amount, timestamp) VALUES (?, ?, ?)";
PreparedStatement stmt = conn.prepareStatement(sql);
String id = args[0];
int len = id.length();
java.sql.Date dt = new java.sql.Date(new java.util.Date().getTime());
stmt.setString(1, id);
stmt.setDouble(2, id.length());
// I think the problem is here - the JDBC driver doesn't properly map dates to Access???
stmt.setDate(3, dt);
stmt.execute();
stmt.close();
conn.close();And I get the following error:
java.sql.SQLException: [Microsoft][ODBC Microsoft Access
Driver] Syntax error in INSERT INTO statement.
at sun.jdbc.odbc.JdbcOdbc.createSQLException (JdbcOdbc.java:6879)
at sun.jdbc.odbc.JdbcOdbc.standardError (JdbcOdbc.java:7036)
at sun.jdbc.odbc.JdbcOdbc.SQLExecDirect (JdbcOdbc.java:3065)
at sun.jdbc.odbc.JdbcOdbcStatement.execute (JdbcOdbcStatement.java:338)
at TestWritingDate.main(TestWritingDate.java:31) I'm virtually certain this is a translation problem with
the java.sql.Date and the JDBC driver. But I can't seem
to overcome this. Any help is DESPERATELY needed.
Thanks.
MattThat was it....thanks...didn't even consider that....perhaps I should start using class names that are already in use too :-). Thanks again...
Maybe you are looking for
-
How can I put songs of a different album together?
I've got an album and I'm trying to put a missing song in the same group, but iTunes keeps separating it.
-
How many apps can be open at one time?
My friend did not know how to close apps. I showed her and was shocked at how many she had open at one time. Everything since she got her ipad over a year ago. She must have had 30 games, pictures, internet, lists, contacts, mail, video, everything w
-
I'm having a hard time retreiving my contacts...
...from my SIM card. I know iPhone's don't save contacts to a SIM card, but I am having a really difficult time figuring out Bluetooth. I have a LG Trax phone that I want to transfer the contacts over to my iPhone. Any help, with detail, would be gre
-
Mail loads on iPhone & iPad but not Macbook Pro
Mail is received in iPad & iPhone Inbox but suddenly stopped showing up on Macbook Pro. This started happening last week but previous to that, it worked perfectly. Any ideas, please? Thanks.
-
Regarding acknowledgement without using BPM
Hi, regarding acknowledgement without using BPM, i've read all realated document sap lib, but i am not clear on it. what step do i have to follow? 1. IDOC to Java server proxy? 2. RFC to Java Server Proxy? 3. ABAP proxy to SOAP? thanks & regards denn