Getting current time in Java for inserting to MySQL

By: Emiley J. Viewed: 153476 times  Printer Friendly Format    

Quite often there is a need to get current time in Java in a specific format. I faced this issue when I had to insert the current time into MySQL. I solved it using a SimpleDateFormat class and a helper function. Here is the code.

The java.text.SimpleDateFormat class is very useful in formatting the date in Java. In my case, I had to convert the date to a format suitable for MySQL insert. So I used this format: String DATE_FORMAT_NOW = "yyyy-MM-dd HH:mm:ss";
Then I created a function that uses this format and converts the current date and returns a string with the current date in this format. Here is the complete code.

1. Step 1: import the required classes

import java.util.Calendar;
import java.text.SimpleDateFormat;

2. Step 2: Initialize the variables

public static final String DATE_FORMAT_NOW = "yyyy-MM-dd HH:mm:ss";

3. Step 3: create the function to get current date and convert to the above format

public static String now() {
Calendar cal = Calendar.getInstance();
SimpleDateFormat sdf = new SimpleDateFormat(DATE_FORMAT_NOW);
return sdf.format(cal.getTime());


4. Step 4: Use the now function to get formatted date in MySQL format.

System.out.println("Now : " + now());

It is as easy as that. With this concept you can use it with different formats.

Most Viewed Articles (in Java )

Latest Articles (in Java)

Comment on this tutorial