简体   繁体   中英

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.

Note: my datetime values are in the format of yyyy-mm-dd hh:mm:ss

You can do some of this in MySQL if you want.

 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.

 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.

An instance of Java's GregorianCalendar class can provide the following method calls, among many others:

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

This should get you where you're going.

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