我有一个问题,我有一个MySQL数据库存储日期和时间在单独的列。但是,在Java代码中,我需要从数据库中以分钟,小时或天计算日期和时间的结果时间戳,然后更新数据库中的相应列。增加Java.sql.date/time的最佳方法是什么?
我目前在Java中使用Java.sql.date和java.sql.time类型。任何人都可以为此提出最佳方法吗?
我可以通过以下实现上述:
public static String addToDateTime(String timestampIn, String increment) {
// Decompose timestamp.
int year = Integer.parseInt(timestampIn.substring(0, 4));
int month = Integer.parseInt(timestampIn.substring(5, 7));
int day = Integer.parseInt(timestampIn.substring(8, 10));
int hours = Integer.parseInt(timestampIn.substring(11, 13));
int mins = Integer.parseInt(timestampIn.substring(14, 16));
int secs = Integer.parseInt(timestampIn.substring(17, 19));
Calendar calendar = new GregorianCalendar(year, month - 1, day, hours, mins, secs);
// Increment timestamp.
if (increment.equals("HOURLY")) {
calendar.add(Calendar.HOUR, 1);
}
else if (increment.equals("DAILY")) {
calendar.add(Calendar.HOUR, 24);
}
else if (increment.equals("WEEKLY")) {
calendar.add(Calendar.HOUR, 168);
}
else if (increment.equals("DO NOT POLL")) {
// Do nothing.
}
// Compose new timestamp.
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String timestampOut = sdf.format(calendar.getTime());
return timestampOut;
}
但宁可少一些原始。
感谢
摩根先生
我喜欢这个。虽然可以用实际的Java sql.date和Java.sql.time变量替换变量timestampin吗?我想消除转换为字符串,然后从字符串结束。 – 2010-06-04 20:16:10
或者对目前我做的空间使用子串测试。 – 2010-06-04 20:39:30