Java MySQL日期时间和joda时间之间的差异
Mysql日期时间如下:2015-05-01 21:36:38.0 和joda当前时间:Java MySQL日期时间和joda时间之间的差异,java,mysql,jodatime,Java,Mysql,Jodatime,Mysql日期时间如下:2015-05-01 21:36:38.0 和joda当前时间: DateTime now = new DateTime().toDateTime(); outputs 2015-05-01T22:08:15.705+02:00 如何计算这两个日期2015-05-01 21:36:38.0和2015-05-01T22:08:15.705+02:00之间的差异(以分钟为单位) 您需要为MySQL时间戳创建DateTimeFormatter。以下是一个例子: Da
DateTime now = new DateTime().toDateTime();
outputs
2015-05-01T22:08:15.705+02:00
如何计算这两个日期2015-05-01 21:36:38.0和2015-05-01T22:08:15.705+02:00之间的差异(以分钟为单位) 您需要为MySQL时间戳创建DateTimeFormatter。以下是一个例子:
DateTimeFormatter formatter = DateTimeFormat.forPattern("YYYY-MM-dd HH:mm:ss.S");
String mysqldatetime = "2015-05-01 21:36:38.0";
DateTime mysqldt = formatter.parseDateTime(mysqldatetime);
DateTime now = new DateTime().toDateTime();
Period diff = new Period(now,mysqldt);
System.out.println(diff.getMinutes());
因为您没有指定字符串时间的时区,假设UTC
public static void main(String[] args) {
String columnData = "2015-05-01 11:36:38.0";
DateTimeFormatter fmt = DateTimeFormat.forPattern("yyyy-MM-dd HH:mm:ss.S");
DateTime dateTime = fmt.withZoneUTC().parseDateTime(columnData);
System.out.println("UTC Time: "+dateTime);
DateTime now = DateTime.now();
int mins = Minutes.minutesBetween(dateTime, now).getMinutes();
System.out.println("Minutes : "+mins);
}
输出:
UTC Time: 2015-05-01T11:36:38.000Z
Current Time 2015-05-01T16:21:41.404-04:00
Minutes : 525
试试这个:
Timestamp _before = (Timestamp) MySQLString.getTime();
Timestamp _now = new Timestamp(new DateTime().getMillis());
System.out.println("CONVERT RESULT MINUTES: "+minutesBetweenTimestamps(_before, _now));
//Pass the variables to this method
public Integer minutesBetweenTimestamps(Timestamp before, Timestamp after){
long _timeGap = after.getTime() - before.getTime();
return (int) (_timeGap / 1000 / 60);
}
无需考虑两个日期时间瞬间的字符串表示形式。假设您正在从列timestamp_col查询数据库中的值,您只需执行以下操作:
ResultSet rs = myStatement.executeQuery();
if (rs.next()) {
Timestamp databaseTime = rs.getTimestamp("timestamp_col");
int minutesInBetween = Minutes.minutesBetween(
new DateTime(databaseTime),
DateTime.now()).getMinutes();
// ...
}
如果您的数据库位于与JVM不同的时区,那么您需要在日历中将正确的db时区传递给rs.getTimestamp。只需将两者作为时间戳长值进行读取和比较,例如:Timestamp ts=new Timestamp now.getmilliss;MySQL日期值的格式是java.sql.TimeStamp吗?@MadProgrammer是的,当创建表时,它是一个时间戳
ResultSet rs = myStatement.executeQuery();
if (rs.next()) {
Timestamp databaseTime = rs.getTimestamp("timestamp_col");
int minutesInBetween = Minutes.minutesBetween(
new DateTime(databaseTime),
DateTime.now()).getMinutes();
// ...
}