【发布时间】:2011-02-27 23:18:39
【问题描述】:
我有一个问题,我的 MySQL 数据库将日期和时间存储在不同的列中。但是,在 Java 代码中,我需要将数据库中日期和时间的结果时间戳增加分钟、小时或天数,然后更新数据库中的相应列。
我目前在 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;
}
但更喜欢不那么原始的东西。
谢谢
摩根先生
【问题讨论】: