Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

datetime datatype in java

Which data type can I use in Java to hold the current date as well as time?. I want to store the datetime in a db as well as having a field in the java bean to hold that.

is it java.util.Date ?

like image 704
akshay Avatar asked Jun 29 '11 05:06

akshay


2 Answers

java.util.Date represents an instant in time, with no reference to a particular time zone or calendar system. It does hold both date and time though - it's basically a number of milliseconds since the Unix epoch.

Alternatively you can use java.util.Calendar which does know about both of those things.

Personally I would strongly recommend you use Joda Time which is a much richer date/time API. It allows you to express your data much more clearly, with types for "just dates", "just local times", "local date/time", "instant", "date/time with time zone" etc. Most of the types are also immutable, which is a huge benefit in terms of code clarity.

like image 61
Jon Skeet Avatar answered Sep 27 '22 20:09

Jon Skeet


import java.util.Date;
import java.text.DateFormat;
import java.text.SimpleDateFormat;

private String getDateTime() {
    DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
    Date date = new Date();
    return dateFormat.format(date);
}
like image 34
Rupok Avatar answered Sep 27 '22 19:09

Rupok