Programming Tutorials

Getting current time in Java for inserting to MySQL

By: Emiley J. in Java Tutorials on 2008-04-11  

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.

Step 1: import the required classes

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

Step 2: Initialize the variables

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

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());

}

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.






Add Comment

* Required information
1000

Comments

No comments yet. Be the first!

Most Viewed Articles (in Java )

Latest Articles (in Java)