Search code examples
javajpaejb-3.0java-ee-6

How to Merge Two Dates in EJB JPA


I am try to Merge Two Dates, Current Date and Another Date in EJB With the help of JPA it's my class UserBean in this class i am prepare one method setExpireDate. This Method are use for merge two dates like a one CurrentDate{new Date()} and another Date {new Date(1,6,0)}

    @Stateless(mappedName = "CMS/UserBean")
public class UserBean implements UserBeanLocal {

    @PersistenceContext(name = "CMS-ejbPU")
    EntityManager em;
@Override
    public boolean setExpireDate(int userId,int planId) 
    {
        try
        {
            EntityBean.User usr = em.find(EntityBean.User.class, userId);


            int day = 20;
            int month = 6;
            int year = 0;

            Date expr = new Date() + new Date(year, month, day);


            usr.setExpireDate(expr);
            return true;
        }
        catch(Exception ex)
        {
            System.out.println("Error are Occure, While Setting the ExpireDate");
            return false;
        }

    }

Solution

  • You should consider using joda-time to handle dates, which is a much better API than what the JDK comes with.

    To manipulate dates with the standard JDK classes, you use the Calendar class:

    Calendar calendar = Calendar.getInstance(); // now
    calendar.add(Calendar.MONTH, 1);
    calendar.add(Calendar.DATE, 2);
    calendar.add(Calendar.YEAR, 3);
    Date result = calendar.getTime();