您的位置:首页 > Web前端

Explain differences among java.util.Date, java.sql.Date, java.sql.Time, and java.sql.Timestamp?

2008-10-27 14:19 579 查看
Explain differences among java.util.Date, java.sql.Date, java.sql.Time, and java.sql.Timestamp?

java.util.Date

|
java.sql.Date java.sql.Time java.sql.Timestamp
java.util.Date - class supports both the Date (i.e. year/month/date etc) and the Time (hour, minute, second, and millisecond) components.
java.sql.Date - class supports only the Date (i.e. year/month/date etc) component. The hours, minutes, seconds and milliseconds of the Time component will be set to zero in the particular time zone with which the instance is associated.
java.sql.Time - class supports only Time (i.e. hour, minute, second, and millisecond) component. The date components should be set to the "zero epoch" value of January 1, 1970 and should not be accessed.
java.sql.TimeStamp – class supports both Date (i.e. year/month/date etc) and the Time (hour, minute, second,millisecond and nanosecond) components.
Note: the subtle difference between java.util.Date and java.sql.Date. The java.sql.Date does not have a time component. If you need both date and time, then should use either java.util.Date or java.sql.TimeStamp. To keep track of time Java counts the number of milliseconds from January 1, 1970 and stores it as a long value in java.util.Date class. The GregorianCalendar class provides us a way to represent an arbitrary date. The GregorianCalendar class also provides methods for anipulating dates (date arithmetic, date comparisons etc).


private static SimpleDateFormat sdf = new SimpleDateFormat(
"yyyy-MM-dd HH:mm:ss");
private static final int FIVEMIN = 5 * 60 * 1000;
private static final int ONEYEAR = 365 * 24 * 60 * 60 * 1000;

/* check time format: yyyy-MM-dd HH:mm:ss */
Date scheDate = null;
try {
String time = req.getTime();
scheDate = sdf.parse(time);
}
} catch (Exception e) {
log.error(e, e);
// do something.
}

/* check time between 5 minutes and 1 year */
GregorianCalendar gc = new GregorianCalendar();
if (scheDate != null) {
if (scheDate.getTime() < (gc.getTimeInMillis() + FIVEMIN)
|| scheDate.getTime() > (gc.getTimeInMillis() + ONEYEAR)) {
// do something.
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐