📜  java.sql.Date(1)

📅  最后修改于: 2023-12-03 14:42:21.331000             🧑  作者: Mango

Java.sql.Date

The java.sql.Date class is a subclass of java.util.Date class in the Java programming language. It is used to represent a date (year, month, day) in a SQL database. It provides several constructors and methods to manipulate date objects in Java.

Constructors of java.sql.Date
java.sql.Date(long date)

This constructor initializes a new instance of java.sql.Date with the given milliseconds since January 1, 1970, 00:00:00 GMT represented by a long value.

Example:

long milliseconds = System.currentTimeMillis(); 
java.sql.Date date = new java.sql.Date(milliseconds);
java.sql.Date(int year, int month, int day)

This constructor initializes a new instance of java.sql.Date with the given year, month, and day values.

Example:

int year=2022, month=10, day=12;
java.sql.Date date = new java.sql.Date(year-1900, month-1, day);
Methods of java.sql.Date
static java.sql.Date valueOf(String s)

This method returns a new java.sql.Date object initialized with the given string in the format yyyy-[m]m-[d]d.

Example:

String dateString = "2022-10-12";
java.sql.Date date = java.sql.Date.valueOf(dateString);
int getYear()

This method returns the year of the java.sql.Date object as an integer value. The year is represented with four digits, for example, 2022.

Example:

java.sql.Date date = new java.sql.Date(1234567891234L); //Apr 17, 2009
int year = date.getYear() + 1900; //2022
int getMonth()

This method returns the month of the java.sql.Date object as an integer value. The month value is between 1 and 12.

Example:

java.sql.Date date = new java.sql.Date(1234567891234L); //Apr 17, 2009
int month = date.getMonth() + 1; //10
int getDate()

This method returns the day of the month represented by this java.sql.Date object as an integer value. The day value is between 1 and 31.

Example:

java.sql.Date date = new java.sql.Date(1234567891234L); //Apr 17, 2009
int day = date.getDate(); //12
Conclusion

java.sql.Date class is a very useful class for handling dates in Java. It provides several constructors and methods to work with date objects. This class is widely used in database operations to store and retrieve dates from the SQL database.