我有一个问题,我有一个 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;
}
但更喜欢不那么原始的东西。
Thanks
摩根先生
您可以使用乔达时间。然后,您可以使用 DateTime 的加小时, plusDays, and 加周。对于解析,有日期时间格式 and 日期时间格式化程序。就像是:
DateTimeFormatter fmt = DateTimeFormat.forPattern("YYYY-MM-dd HH:mm:ss");
DateTime dt = fmt.parseDateTime(timestampin);
if (increment.equals("HOURLY")) {
dt = dt.plusHours(1);
}
else if (increment.equals("DAILY")) {
dt = dt.plusDays(1);
}
else if (increment.equals("WEEKLY")) {
dt = dt.plusWeeks(1);
}
String timestampOut = fmt.print(dt);
你可能可以使用类似的东西:
DateTime dt = new DateMidnight(sqlDate).plus(Period.millis(sqlTime.getTime()));
假设 sql.Time 表示自午夜以来的毫秒数。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)