tags:

views:

566

answers:

3

Hi,

I want to fetch the records from MySQL for the current year and month.

I am passing to get the today records

Today: ("recDate","=", new Date());

Like that, how to fetch for current Month and current Year ?

Thanks in advance

  • Gnaniyar Zubair
+1  A: 
import java.util.Calendar;

public class CalendarExample
{
    public static void main(String[] args)
    {
        Calendar cal = Calendar.getInstance();
        int day = cal.get(Calendar.DATE);
        int month = cal.get(Calendar.MONTH) + 1;
        int year = cal.get(Calendar.YEAR);
        int dow = cal.get(Calendar.DAY_OF_WEEK);
        int dom = cal.get(Calendar.DAY_OF_MONTH);
        int doy = cal.get(Calendar.DAY_OF_YEAR);

        System.out.println("Current Date: " + cal.getTime());
        System.out.println("Day: " + day);
        System.out.println("Month: " + month);
        System.out.println("Year: " + year);
        System.out.println("Day of Week: " + dow);
        System.out.println("Day of Month: " + dom);
        System.out.println("Day of Year: " + doy);
    }
}

Here is the result of this example:

Current Date: Thu Dec 29 13:41:09 ICT 2005 Day: 29 Month: 12 Year: 2005 Day of Week: 5 Day of Month: 29 Day of Year: 363

Warrior
Please do not use other peoples code withtout giving them credit: http://www.kodejava.org/examples/21.html
Espo
Nothing wrong in learning from others and guiding other who don't know.
Warrior
Espo
and he hasn't even answered the question...
Alnitak
A: 

I don't know the exact functions in mysql but you google them. In your SQL in java code use CONVERT function on the date column and equate it to current date which alos uses the convert function. The Convert function will strip down the dates to only month and year and that way it will compared as string only.

Bhushan
+4  A: 

There's no need to pass parameters, MySQL can work out for itself what the current year and month is:

SELECT * FROM table
WHERE  YEAR(recDate) =  YEAR(CURDATE())
  AND MONTH(recDate) = MONTH(CURDATE())

or, alternatively,

SELECT * FROM table
WHERE DATE_FORMAT(recDate, '%Y%m') = DATE_FORMAT(NOW(), '%Y%m')
Alnitak