简体   繁体   中英

Difference between MySQL datetime and joda time

Mysql date time is like this: 2015-05-01 21:36:38.0

And joda current time:

DateTime now = new DateTime().toDateTime();
outputs
2015-05-01T22:08:15.705+02:00

How to get the difference between these 2 dates 2015-05-01 21:36:38.0 and 2015-05-01T22:08:15.705+02:00 in minutes?

You need to create a DateTimeFormatter for your MySQL timestamp. Here is an example:

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

Try this:

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

Since you didn't specify the timezone of the String time, assuming 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);

    }

Output:

UTC Time: 2015-05-01T11:36:38.000Z
Current Time 2015-05-01T16:21:41.404-04:00
Minutes : 525

There is no need to think about the String representation of the two date-time instants. Assuming you are querying the value from the database from column timestamp_col , you can simply do this:

ResultSet rs = myStatement.executeQuery();

if (rs.next()) {
    Timestamp databaseTime = rs.getTimestamp("timestamp_col");
    int minutesInBetween = Minutes.minutesBetween(
            new DateTime(databaseTime),
            DateTime.now()).getMinutes();
    // ...
}

If your database is in a different timezone than the JVM, then you need to pass in the correct db timezone in a Calendar to rs.getTimestamp .

String format = "dd-MMM-yy hh.mm.ss.SSSS"
DateTime dateTime  = DateTime.parse(input,DateTimeFormat.forPattern(format));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM