简体   繁体   中英

How to retrieve the Date variable from oracle database in yyyy-MM-dd HH:mm:ss format and store in Date variable in the same format?

I want to retrieve the Date object from oracle database and store it in Date variable in Java in the same format ?

PS ; Data type of the variable should be Date only but, need to have the format yyyy-MM-dd HH:mm:ss .

Date class will store internally the date as a long integer. If you want to convert it to string you can use a DateFormat

DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String dateFormatted = df.format(new Date());
Date date = df.parse(dateFormatted);

If the database is set up correctly, you should be able to simply retrieve a date column into a date variable. Formatting considerations should be non-applicable at the database access level; they should be a non-issue.

Formatting is something you do in order to display the date to the user.

Formatting is also something that various tools do, to show you the contents of your database, or the contents of your date object, so this can cause a bit of confusion, as it may lead you to believe that the date column has a certain format, or that your date variable has a certain format. But they don't.

The problems start when things are done wrongly at the database level. If the database column is not actually of a temporal data type, but of CHAR type instead, then of course formatting plays a role. But then we are not talking about "Retrieving a date object from the oracle database", we are talking about retrieving a string from the database and converting it to a date. However, you have no told us nothing about the structure of your table, so we cannot speculate about that.

So, with the information that you have given, the right answer is simply "just fetch the date column into a date variable". Please provide more information if you need a different answer.

As per the comments, you might want to create a CustomDate class that prints the value in the specified format:

public class CustomDate extends Date{
    private static final DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    @Override
    public String toString() {
        return df.format(this);
    }

}

Instead of creating instances of Date, try to use CustomDate. It'll be equivalent in your code.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM