简体   繁体   English

如何在mysql和Java中修改比较和操作datetime值?

[英]How to modify compare and manipulate datetime values in mysql and Java?

I have a column in my database which is of datetime type.I want to first extract the records and then I want to compare this datetime value to a reference datetime value and then monitor certain activities within +- 2 months of the corresponding datetime value(2 months before that datetime and 2 months after the datetime).I am able to get the records but I am clueless about manipulating the datetime value.I read this post ( How to change time in datetime? ) but I am not able to get as it only changes the time and not the date part of the datetime.Also since the post is for C#, I am unable to do the same in Java. 我的数据库中有一列属于datetime类型的列。我想先提取记录,然后再将此datetime值与参考datetime值进行比较,然后监视相应datetime值的+-2个月内的某些活动(该日期时间之前的2个月和该日期时间之后的2个月)。我能够获取记录,但是对于操纵datetime值一无所知。我读了这篇文章( 如何更改datetime中的时间? ),但我无法获取因为该帖子仅更改时间,而不更改datetime的日期部分。此外,由于该帖子是针对C#的,因此我无法在Java中执行相同的操作。

Note: my datetime values are in the format of yyyy-mm-dd hh:mm:ss 注意:我的日期时间值的格式为yyyy-mm-dd hh:mm:ss

You can do some of this in MySQL if you want. 您可以根据需要在MySQL中执行某些操作。

 SELECT whatever FROM whattable
  WHERE whatdatetime > targettime - INTERVAL 2 MONTH
   AND  whatdatetime < targettime + INTERVAL 2 MONTH

This will retrieve records in the specified four-month range. 这将检索指定四个月范围内的记录。

Or you can do this to use MySQL's date arithmetic. 或者,您可以执行此操作以使用MySQL的日期算术。

 SELECT whatdatetime, 
        whatdatetime - INTERVAL 2 MONTH AS startrange,
        whatdatetime + INTERVAL 2 MONTH AS endrange

To do this stuff in Java, you're going to need to use the java.util.Calendar abstract class, implemented by java.util.GregorianCalendar. 要在Java中完成这些工作,您将需要使用由java.util.GregorianCalendar实现的java.util.Calendar抽象类。

An instance of Java's GregorianCalendar class can provide the following method calls, among many others: Java的GregorianCalendar类的实例可以提供以下方法调用,其中包括:

 calendar.add(Calendar.MONTH, -2);
 calendar.add(Calendar.MONTH,  2);

This should get you where you're going. 这应该可以让您到达目的地。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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