1

I tried using java.util.Date and java.sql.Date but in both the cases time part is not getting saved.

if date is 2015-11-16 17:53:49.6

it is saving it as 2015-11-16 00:00:00.000 in SQL Server.

2
  • Do you mind using varchar instead of date? Commented Nov 16, 2015 at 12:33
  • What technology / library do you use for database connection? Commented Nov 16, 2015 at 12:35

4 Answers 4

1

From the docs of java.sql.Date as it represents only date not the time(so the time value will be 00:00:00.000 which you are getting). So you have to add the time explicitly in your code or better use java.sql.Timestamp

To conform with the definition of SQL DATE, the millisecond values wrapped by a java.sql.Date instance must be 'normalized' by setting the hours, minutes, seconds, and milliseconds to zero in the particular time zone with which the instance is associated.

Sign up to request clarification or add additional context in comments.

Comments

0

Does using java.sql.Timestamp work ?

Check the data type of the SQL Server column too.

https://msdn.microsoft.com/en-us/library/ms378878(v=sql.110).aspx - This might help.

Comments

0

You can use SQL GETDATE() function to get the current data and time.You can also fix it as default value while defining the table. Example:

CREATE TABLE Orders
(
OrderId int NOT NULL PRIMARY KEY,
ProductName varchar(50) NOT NULL,
OrderDate datetime NOT NULL DEFAULT GETDATE()
)

Moreover for insert statement you can use the query like this

INSERT INTO Orders (ColumnName) VALUES (GETDATE());

Comments

0

You can achive the same with the conversion like this

import java.text.SimpleDateFormat;

import java.util.Date;

class A3{
    public static void main(String[] args) throws Exception{

        Date date = new Date();
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("dd-M-yyyy hh:mm:ss a");
        String dateWithSeconds = simpleDateFormat.format(date);
        System.out.println(dateWithSeconds);
    }
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.