Home Tutorial Java Core JDBC: Get current Date and Time Example

 
 

Share on Google+Share on Google+
JDBC: Get current Date and Time Example
Posted on: September 28, 2012 at 12:00 AM
Advertisement
In this section, you will learn how to get current Date and current time using JDBC API.

JDBC: Get current Date and Time Example

In this section, you will learn how to get current Date and current time using JDBC API.

Get current Date and Time :

CURDATE() : For current date you can use CURDATE(). It returns current date in the format 'YYYY-MM-DD'
You can get current date by writing  - SELECT CURDATE()
You will get output - 2012-09-28

CURTIME() : For current time you can call CURTIME(). It returns current time in the format of 'HH:MM:SS'.
You can get current date by writing  - SELECT CURTIME();
You will get output - 17:04:30

Example :  In this example we are selecting current date and current time by using MySql methods CURDATE() and CURTIME().

package jdbc;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

class CurrentDateTime{
	public static void main(String[] args) {
		System.out.println("Get Current Date and Time Example...");
		Connection con = null;
		Statement statement = null;
		ResultSet rs = null;
		String url = "jdbc:mysql://localhost:3306/";
		String dbName = "students";
		String driverName = "com.mysql.jdbc.Driver";
		String userName = "root";
		String password = "root";
		try {
			// Connecting to the database
			Class.forName(driverName);
			con = DriverManager.getConnection(url + dbName, userName, password);
			try {
				// Creating object of Statement
				statement = con.createStatement();

				// Get current date and current time
				String sql = "SELECT CURDATE(),CURTIME()";
				rs = statement.executeQuery(sql);
				while (rs.next()) {
					System.out.println("Current Date : "+ rs.getDate(1));
					System.out.println("Current Time : "+ rs.getTime(2));
				}
			} catch (SQLException e) {
				System.out.println(e);
			}
			con.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}

Output :

Get Current Date and Time Example...
Current Date : 2012-09-28
Current Time : 17:04:30
Advertisement

Related Tags for JDBC: Get current Date and Time Example:


Follow us on Twitter, or add us on Facebook or Google Plus to keep you updated with the recent trends of Java and other open source platforms.

Posted on: September 28, 2012

Recommend the tutorial

Advertisements Advertisements
 

 

 

DMCA.com