如何将系统日期与数据库mysql中的日期进行匹配

时间:2014-11-15 07:17:42

标签: java mysql date

我有一个名为work的数据库,使用mysql创建,其中创建了一个名为register的表。它包含一个列更新。我从像这样的java swing中访问了表

    conn=ConnectionDB.conn();
    Date d=sysdate();
    String sql="select renewdate from register";
    try
    {
        ps=conn.prepareStatement(sql);
        ResultSet rs=ps.executeQuery();
        Date dates;
        while(rs.next())
        {
            dates = rs.getDate("renewdate");
            System.out.println(dates);
            if(dates==d)
            {
               SendMailTLS.sendMail();
            }
        }
    }

我的问题是在续订等于系统日期时发送电子邮件。我使用函数sysdate()生成当前日期并将其分配给d。还使用dates = rs.getDate(" renewdate")在表中为日期分配续订。 我的问题是我无法匹配d和日期,因此无法发送电子邮件。你能帮助我如何匹配d和日期。 我尝试了while(rs.next())获得表寄存器中的所有日期。但是使用if(dates == d)无法与d匹配。我也试过(rs.next()),但它只从表中获取第一个续订。那么如何检查续订的所有值并与当前发送消息的日期相匹配

3 个答案:

答案 0 :(得分:1)

只需将查询字符串更改为

即可
// NOW() in mysql will get the current date and time. So here you get only renewdates matched with current date and time
String sql="select renewdate from register where renewdate = NOW()";

// If you want to compare only with date not time, then go with 
String sql="select renewdate from register where renewdate = CURDATE()";

上述代码中不需要此if(dates == d)。在while条件中有下一个元素后立即发送邮件。

答案 1 :(得分:0)

好的代码!所以:

将日期值保存为以下字符串:

Date   d=sysdate();
String strDate1 = d.toString();
String strDate2 = rs.getDate("renewdate").toString;

然后比较它:

strDate1.equals(strDate2);

因为字符串包含对“单词”的引用,而不是“单词”本身,==操作者会做其他事情;

请你把这个应用程序的全部代码发给我们,因为从中学习是件好事吗?

答案 2 :(得分:0)

如果你想在代码中这样做,可以采用以下方法: -

使用以下代码将从数据库获取的日期转换为java.util.Date对象(假设日期存储在GMT中):

SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
formatter.setTimeZone(TimeZone.getTimeZone("GMT"));
Date dateInDB = formatter.parse(dates);

然后,您只需使用java.util.Date equals方法将ddateInDB进行比较即可。

如果您想在比较两个日期时忽略时间部分,请调用以下方法(将时间部分设置为00:00:00),并使用equals方法中的返回日期:

public static Date getZeroTimeDate(Date dateWithTime) {
    Date res = dateWithTime;
    Calendar calendar = Calendar.getInstance();

    calendar.setTime( dateWithTime );
    calendar.set(Calendar.HOUR_OF_DAY, 0);
    calendar.set(Calendar.MINUTE, 0);
    calendar.set(Calendar.SECOND, 0);
    calendar.set(Calendar.MILLISECOND, 0);

    res = calendar.getTime();

    return res;
}

这样它也不会使用任何弃用的方法。

希望这有帮助!