通过日期时间字段之间的减法选择模型

时间:2017-10-16 14:04:51

标签: mysql ruby-on-rails ruby datetime

我有一个名为' schedule'的mySQL表。其中包含日期时间格式的字段 time_start time_end

我需要从数据库中获取模型,在Ruby on Rails上下文中减法将超过4小时。例如:

if ($R1D2 = $today):

如何使用Active Record执行此操作?如果不可能那么我怎么能用mySQL查询呢?

4 个答案:

答案 0 :(得分:0)

我不知道或Rails(我相信Rails是不可能的),但它很容易用SQL:

Schedule.where("TIMESTAMPDIFF(HOUR, time_end, time_start) > 4")

TIMESTAMPDIFF文档。

答案 1 :(得分:0)

只要你使用mysql就行了。

Schedule.where("DATE_SUB(time_end, INTERVAL 4 HOUR) > time_start")

参考:https://dev.mysql.com/doc/refman/5.7/en/date-and-time-functions.html#function_date-add

答案 2 :(得分:0)

MySQL有两个日期差异的函数:

package com.example.hp.mirocareltd;

import android.content.DialogInterface;
import android.content.Intent;
import android.location.LocationManager;
import android.provider.Settings;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;


abstract class BaseMethods extends AppCompatActivity {
    public void getGPS(){
        LocationManager service = (LocationManager) getSystemService(LOCATION_SERVICE);
        boolean enabled = service
                .isProviderEnabled(LocationManager.GPS_PROVIDER);

        // check if enabled and if not send user to the GSP settings
        // Better solution would be to display a dialog and suggesting to
        // go to the settings
        if (!enabled) {
            AlertDialog alertDialog = new AlertDialog.Builder(this).create();
            alertDialog.setTitle("GPS Location");
            alertDialog.setMessage("Turn ON your GPS location to Access!");
            alertDialog.setButton(AlertDialog.BUTTON_NEUTRAL, "OK",
                    new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog, int which) {
                            dialog.dismiss();
                            //finish();
                            Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
                            startActivity(intent);
                        }
                    });
            alertDialog.show();
        }
    }
}

您可以使用以下内容:

SELECT TIMEDIFF('2007-12-31 10:02:00','2007-12-30 12:01:01');
-- result: 22:00:59.


SELECT TIMESTAMPDIFF(SECOND,'2007-12-30 12:01:01','2007-12-31 10:02:00'); 
-- result: 79259  the difference in seconds with the time.

不确定是否有效,但您可以尝试一下。希望这有帮助!

答案 3 :(得分:0)

您可以使用MySQL的TIMEDIFF功能:

Move-Item