1

I need to get the number of days in a month from the Register table. Im using the following SQL Query :

SELECT DateTo::Date-DateFrom::Date AS DaysInMonth FROM Register;

While executing it in SQL Editor of PostgreSQL Im getting the following result : enter image description here

While executing the same through java code Im getting the result as 29 days instead of 29 Im adding the java code here

sql = " SELECT DateTo::Date-DateFrom::Date AS DaysInMonth FROM Register; "                  
    PreparedStatement pstmt = null;
    ResultSet rs = null;                
    try {
        pstmt = DB.prepareStatement(sql, null);
        pstmt.setInt(1, payReg.getC_Period_ID());
        rs = pstmt.executeQuery();                      
        while (rs.next()){                          
            System.out.println(rs.getString("DaysInMonth"));
        }
    }catch (SQLException e){
        e.printStackTrace();
    }

What may be the reason..? I need to get just 29 from the java execution. How do I get it..? Thanks in advance.

1

3 Answers 3

2

Try this.. DATE_PART('days',DATE_TRUNC('month', DateTo) - DATE_TRUNC('month', Datefrom)) as DaysInMonth

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you Sreekuttan. Its working properly, but what may be the problem while executing it through java.?
0

Did you try

rs.getInt("DaysInMonth")

Instead of

rs.getString("DaysInMonth")

As you are expecting an Integer.

1 Comment

It will throw an Exception saying "bad value for int : 29 days"
0

Postgres certainly returns an integer when subtracting two dates. It looks like the cast did not happen. I suspect that :: in the PostgreSQL specific syntax DateTo::Date has special meaning in your client. Try the SQL standard syntax for casting:

Also demonstrating better ways to ...

... get the number of days in a month

EXTRACT(day FROM cast(DATE_TRUNC('month'
                                  ,now() + interval '1 month') AS date) - 1);

Better yet, use this simpler and faster expression that doesn't need a cast at all:

EXTRACT(day FROM DATE_TRUNC('month', now()) + interval '1 mon - 1 day');

Set log_statement = ALL temporarily and check in the Postgres DB logs what the server actually gets.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.