• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

SQL Dates

 
Owen Martin
Greenhorn
Posts: 14
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi there, I am using JDBC and a SQL database.

I have an alarm field in the database which is of date/time.

On my front end I have a String of the format, '01-05-2012' and I am simply inserting it into the database by using the INSERT into X Values ('01-05-2012)

Is this the right way to go about storing a date? Do I need to declare anything the database?
 
Patryk Sosinski
Greenhorn
Posts: 18
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Use to_date() function:

create table test (id number primary key, d date);

insert into test values (1, to_date('01-03-2012', 'DD-MM-YYYY'));
 
Owen Martin
Greenhorn
Posts: 14
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Get a incorrect syntax error when trying to use to_date, I am using SQL Server and SQL Server Management Studio
 
Rob Spoor
Sheriff
Pie
Posts: 20514
54
Chrome Eclipse IDE Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I'd prefer to use a PreparedStatement and its setDate method. That's guaranteed to work in all database servers with a JDBC driver:

Alternatively, in MS SQL Server you can use strings to specify the date. You don't want to use "01-05-2012" as the value though, as the server's region determines whether that's January 5th or May 1st. What always works is to use yyyy-MM-dd: "2012-01-05".
 
Patryk Sosinski
Greenhorn
Posts: 18
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Ah, sorry. You have to use convert function but i cant write more - dont have MS SQL installed.
Check this out:
http://www.sqlusa.com/bestpractices/datetimeconversion/
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic