I am trying to store date in sql server 2005
i am used "datetime" data type in sql server
and in java program i am passing string as date
ex.
String DateStr = "12/12/2013";
Date d = new Date();
java.sql.Date d1 = new java.sql.Date(d.getTime());
String sql = "INSERT INTO info (date) VALUES ( ? )";
try {
pstmt = con.prepareStatement(sql);
pstmt.setDate(1, d1);
pstmt.executeUpdate();
} catch (SQLException e) {
System.out.println("Error:" + e);
}
the above code is working...but i want to use String DateStr = "12/12/2013";
insted of d.getTime() bcoz i passed date as string to java function by using jquery datepicker
You need to use a SimpleDateFormat to parse your String to a date and then use that date.
Date d = new SimpleDateFormat("dd/MM/yyyy").parse(DateStr); // This throws a ParseException
// Rest everything stays pretty much the same
java.sql.Date d1 = new java.sql.Date(d.getTime());
...
public long convertLong(String value) {
DateFormat formatter = new SimpleDateFormat("dd/MM/yyyy");
Date getDate = null;
long returnDate = 0l;
try {
getDate = (Date) formatter.parse(value);
returnDate = getDate.getTime();
} catch (ParseException e) {
e.printStackTrace();
}
return returnDate;
}
Input: 12/12/2013
Output: 1386786600000
First convert string in datetime object than you can directly pass d1 to your code
String DateStr = "12/12/2013";
DateTimeFormatter formatter = DateTimeFormat.forPattern("dd/MM/yyyy ");
DateTime dt = formatter.parseDateTime(DateStr);
String sql = "INSERT INTO info (date) VALUES ( dt )";
try {
pstmt = con.prepareStatement(sql);
pstmt.setDate(1, d1);
pstmt.executeUpdate();
}
catch (SQLException e) {
System.out.println("Error:" + e);
}
Related
I am a total noob to java and sqlite. This should be simple, but I have tried and searched and can't get it to work. I have a date field in SQL that I am formatting as a sql date (MM/dd/yy). I want to delete based on a date passed. For the moment, I am only trying to display rows based on a passed date.
My code to run the query is:
String query = "select * from Peter1Score where DateSort='"+convertSQLDate("09/20/15")+"'";
PreparedStatement pst = connection.prepareStatement(query);
ResultSet rs = pst.executeQuery();
My converSQLDate() is:
public static java.sql.Date convertSQLDate (String sqlDateIn)
{
java.sql.Date returnDate = null;
SimpleDateFormat formatter = new SimpleDateFormat("MM/dd/yy");
Date parsed;
try
{
parsed = formatter.parse(sqlDateIn);
java.sql.Date sqlDate = new java.sql.Date(parsed.getTime());
returnDate = sqlDate;
}
catch (ParseException e)
{
e.printStackTrace();
}
return returnDate;
}
I am passing 09/20/15 just for test. I have a record with that date, but it doesn't get selected.
You're not binding any variables into the statement (using the setXY() methods of PreparedStatement). Instead, you're concatenating a string value (result of Date.toString()) into the query literal.
Try this instead:
String query = "select * from Peter1Score where DateSort=?";
PreparedStatement pst = connection.prepareStatement(query);
pst.setDate(1, convertSQLDate("09/20/15"));
public Date getTransactionDate()
{
System.out.println("Enter the transaction Date");
String date = sc.next();
DateFormat df = DateFormat.getDateInstance();
String s1 = df.format(date);
Date d1 = null;
try
{
d1 = (Date) df.parse(s1);
} catch (java.text.ParseException e)
{
// TODO Auto-generated catch block
System.out.println(e.getMessage());
}
return d1;
}
Date d2 = new PreparedStmnt().getTransactionDate();
public static void addTransaction(Connection connection, PreparedStatement preparedStatement , long transac_Id , Date transac_date)
throws SQLException
{
String sqlQuery = "INSERT INTO TRANSACTIONS VALUES (?,?)";
preparedStatement = connection.prepareStatement(sqlQuery);
preparedStatement.setLong(1, transac_Id);
preparedStatement.setDate(2, transac_date);
preparedStatement.executeUpdate();
}
Its a Simple Transaction entry where i want the user to provide date at runtime and then store that in the database.But while doing so, I'm getting a bug saying:
Exception in thread "main" java.lang.IllegalArgumentException: Cannot format given Object as a Date
at java.text.DateFormat.format(Unknown Source)
at java.text.Format.format(Unknown Source)
at bluePrint.PreparedStmnt.getTransactionDate(PreparedStmnt.java:76)
at bluePrint.PreparedStmnt.main(PreparedStmnt.java:30)
Well this is my first project m working on. So, please help me.
you should use sc.nextLine() Instead sc.next() because its not consider space
you can try like
System.out.println("Enter the transaction Date");
String string = "January 2, 2010";
Scanner sc = new Scanner(System.in);
string = sc.nextLine();
System.out.println(string);
DateFormat format = new SimpleDateFormat("MMMM d, yyyy", Locale.ENGLISH);
try {
Date date = format.parse(string);
System.out.println(date);
} catch (java.text.ParseException e) {
// TODO Auto-generated catch block
System.out.println(e.getMessage());
}
this worked for me. entered date format January 2, 2010
The error here shows that the data type criteria mismatch
Please tell how to filter the date using two text fields
The error at dateFormat = new SimpleDateFormat("dd/MM/YYYY").parse(G); shows that no method found for parse (Date)
String a=jTextField1.getText();
String b=jTextField2.getText();
Date n=new Date();
SimpleDateFormat date = new SimpleDateFormat("dd/MM/YYYY");
DefaultTableModel tm=(DefaultTableModel)jTable1.getModel();
try
{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Connection con;
con = DriverManager.getConnection ("jdbc:odbc:NAMT","Navi","1234");
PreparedStatement ps=con.prepareStatement(
"select * from [Sheet1$] where SEVERITY='Critical' and DATE BETWEEN '"+a+"'and'"+b+"'" );
try (ResultSet rs =ps.executeQuery())
{
while(rs.next())
{
String B=rs.getString("NetworkElement");
String E=rs.getString("Severity");
java.util.Date G = rs.getDate("DATE");
java.util.Date dateFormat;
dateFormat = new SimpleDateFormat("dd/MM/YYYY").parse(G);
tm.addRow(new Object[] {B,E,G});
}
}
con.close();
}
catch(Exception x)
{
System.out.println(x);
}
SimpleDateFormat.parse()
expects a String, not a Date.
SimpleDateFormat.fomat()
takes a Date-Object.
When I convert String date like "18/09/13,02:01:51"
Using this method:
public static Date stringToDateFormat(String dateString) {
Date date = null;
try {
date = new SimpleDateFormat("dd/MM/yy,hh:mm:ss").parse(dateString);
} catch (ParseException e) {
e.printStackTrace();
}
return date;
}
When I save this convert this date object to SQL Date and store it in PostgreSQL Database, I lose the time
2013-09-18 00:00:00
Here the DB insertion code"
String query = "INSERT INTO My_Table(my_date) VALUES (?)";
Date date = stringToDateFormat("18/09/13,02:01:51");
preparedStatement = connection.prepareStatement(query);
preparedStatement.setDate(1, new java.sql.Date(date.getTime()));
preparedStatement.executeUpdate();
Is it coding problem or DB configuration?
Thanks.
Your date string does not specify ms and is being rounded.
18/09/13,02:01:51 == 1379458917000
18/09/13,02:01:51.590 == 1379458917590
Update:
A format string which captures MS would be: dd/MM/yy,hh:mm:ss.SSS
I get a returned parsed JSON result with string values in the form of dates like "27-11-2012" which i parse to a date Object. my code for this is:
public Date stringToDateReport(String s){
//Log.d(TAG, "StringToDateReport here is " + s);
DateFormat format;
Date date = null;
//if(s.matches(""))
format = new SimpleDateFormat("dd-MMM-yyyy");
try {
date = (Date)format.parse(s);
} catch (ParseException e) {
e.printStackTrace();
}
return date;
}
now my issue is, a feature has been implemented that sometimes the json only returns a year object like "2012" and is giving me an "ParseException: Unparseable date" as expected. I was thinking of using regex to match the string pattern and parse from there, but not sure how to do that. Any ideas and also anyway to parse only year in a DateFormat?
I'd try:
public Date stringToDateReport(String s){
DateFormat format;
Date date = null;
format = new SimpleDateFormat("dd-MM-yyyy");
if(s.length()==4) {
format = new SimpleDateFormat("yyyy");
}
try {
date = (Date)format.parse(s);
} catch (ParseException e) {
//you should do a real logging here
e.printStackTrace();
}
return date;
}
The logic behind is to check if the string is only 4 long, then apply the different format. In this case, this easy method is sufficient, but in other methods, the use of regexes might be required.
Try this code
public Date stringToDateReport(String s){
//Log.d(TAG, "StringToDateReport here is " + s);
DateFormat format;
Date date = null;
if(s.indexOf("-") < 0){
format = new SimpleDateFormat("yyyy");
}else{
format = new SimpleDateFormat("dd-MMM-yyyy");
}
try {
date = (Date)format.parse(s);
} catch (ParseException e) {
e.printStackTrace();
}
return date;
}
Is there the possibility in have another format in the String s ? Or just these two?
public Date stringToDateReport(String strDate){
DateFormat formatnew SimpleDateFormat("dd-MM-yyyy");
Date date = null;
if(strDate.length()==4) {
format = new SimpleDateFormat("yyyy");
}
try {
date = (Date)format.parse(strDate);
} catch (ParseException e) {
//error parsing date
e.printStackTrace();
}
return date;
}
then call it like this :
String strDate = yourJson.getString("date");
Date d = stringToDateReport(strDate);