JDBC : Current Date


 

JDBC : Current Date

In this section, you will learn query for current date.

In this section, you will learn query for current date.

JDBC : Current Date

In this section, you will learn query for current date.

Display Current Date :

There are various methods provided by MYSQL to get current date. These are CURRENT_DATE, CURRENT_DATE(), CURRENT_TIMESTAMP, CURRENT_TIMESTAMP(), NOW(), SYSDATE().

CURDATE() , CURRENT_DATE, CURRENT_DATE() functions  return the current date in format 'YYYY-MM-DD'.

CURRENT_TIMESTAMP, CURRENT_TIMESTAMP(), NOW() functions return the current date and time as a value in 'YYYY-MM-DD HH:MM:SS'

SYSDATE()  : It returns the current date and time as a value in 'YYYY-MM-DD HH:MM:SS' .

Example : You can use any of the above function to get current date. In this example we are using CURRENT_TIMESTAMP.

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.Date;

public class JDBCCurrentDate {
	public static void main(String[] args) {
		System.out.println("Current Date Example...");
		Connection conn = null;
		String url = "jdbc:mysql://localhost:3306/";
		String dbName = "employees";
		String driverName = "com.mysql.jdbc.Driver";
		String userName = "root";
		String password = "root";
		Statement statement = null;
		ResultSet rs;
		try {
			Class.forName(driverName);
			conn = DriverManager
					.getConnection(url + dbName, userName, password);
			statement = conn.createStatement();
			String sql = "SELECT CURRENT_TIMESTAMP";
			rs = statement.executeQuery(sql);
			System.out.print("Today date is - ");
			while (rs.next()) {
				Date date = rs.getDate(1);
				System.out.println(date);
			}
			conn.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}

Output :

Current Date Example...
Today date is - 2012-10-12

Ads