How to get current TimeStamp in Java

There are several ways to get the current timestamp in Java. This example works in Java6, 7 and 8.

Please note that Java 8 contains now a simpler and more efficient date and time API.

// Using the java.sql.Timestamp class
Timestamp timestamp = new Timestamp(System.currentTimeMillis());
System.out.println(timestamp);

// Using the Date object
Date date = new Date();
System.out.println(new Timestamp(date.getTime()));

 

How to connect to a database using JDBC

This example shows how to connect to a database using JDBC. (In this example we will connect to Oracle database) .

You will need to add the odbc{x}.jar library to your classpath, downloadable from Oracle’s website.

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

public class JdbcExample {

 public static void main(String[] args) {
  
  try{
  	// register the driver
  	Class.forName("oracle.jdbc.driver.OracleDriver");
  	// create the connexion
  	Connection connection
            =DriverManager.getConnection(
               "jdbc:oracle:thin:@localhost:1521:xe", "system", "pwd"
                );
  } catch (ClassNotFoundException e) {
    // the driver was not found
    e.printStackTrace();
  } catch (SQLException e) {
    // Error when connecting to database
    e.printStackTrace();
  }
 }

}

 

What is new in Java 8

Java 8 is a major release of the java programming language. It introduces new features and enhancements. The most significant ones are the following.

Lambda expressions

New Date and Time API

Method references

Default methods

Repeating annotations

Type annotations

Stream API

Optional

Narshon

new tools and utilities