MySQL 日期时间和 joda 时间之间的差异

Difference between MySQL datetime and joda time

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.02015-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
String format = "dd-MMM-yy hh.mm.ss.SSSS"
DateTime dateTime  = DateTime.parse(input,DateTimeFormat.forPattern(format));

试试这个:

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);
}

无需考虑两个日期时间瞬间的 String 表示。假设您要从数据库中查询 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 处于不同的时区,那么您需要在 Calendarrs.getTimestamp 中传递正确的数据库时区。