Example usage for java.util Calendar DATE

List of usage examples for java.util Calendar DATE

Introduction

In this page you can find the example usage for java.util Calendar DATE.

Prototype

int DATE

To view the source code for java.util Calendar DATE.

Click Source Link

Document

Field number for get and set indicating the day of the month.

Usage

From source file:com.krawler.common.util.SchedulingUtilities.java

public static Date calculateEndDate(Date sDate, String duration, int[] NonWorkDays, String[] CmpHoliDays,
        String userid) throws ParseException, ServiceException {
    Date dt = new Date();
    java.text.SimpleDateFormat sdfLong = new java.text.SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    String edate = "";
    Calendar c = Calendar.getInstance();
    dt = sDate;// w  w w .j a  va2s.  co m
    double d = getDurationInDays(duration);
    c.setTime(dt);
    if (d > 0) {
        c.add(Calendar.DATE, (int) (d - 1));
    } else {
        c.add(Calendar.DATE, (int) d);
    }
    Date nDate = dt;
    int flag = 0;
    int nwd = nonWorkingDays(nDate, c.getTime(), NonWorkDays, CmpHoliDays);
    while (nwd != 0) {
        nDate = c.getTime();
        if (nwd == 1 && flag == 0) {
            c.add(Calendar.DATE, nwd);
            flag = 1;
        } else {
            c.add(Calendar.DATE, nwd - 1);
        }
        nwd = nonWorkingDays(nDate, c.getTime(), NonWorkDays, CmpHoliDays);
    }
    dt = c.getTime();
    edate = sdfLong.format(dt);
    if (Arrays.binarySearch(NonWorkDays, (c.get(Calendar.DAY_OF_WEEK) - 1)) > -1) {
        edate = getNextWorkingDay(edate, NonWorkDays, CmpHoliDays);
    }
    dt = sdfLong.parse(edate);
    return dt;
}

From source file:net.granoeste.commons.util.DateUtils.java

/**
 * ?????//from  www  . j a va2 s  . c om
 *
 * @param cal
 * @param amount ex) last month : -1. the current month : 0. the next month : 1
 */
public static void shiftDateOnMondayOfAWeekAtTheBeginningOfTheMonth(final Calendar cal, final int amount) {

    cal.set(Calendar.DATE, 1);
    cal.add(Calendar.MONTH, amount);
    if (cal.get(Calendar.DAY_OF_WEEK) == Calendar.SUNDAY) {
        cal.add(Calendar.DATE, -6);
    } else {
        cal.add(Calendar.DATE, -cal.get(Calendar.DAY_OF_WEEK) + 2);
    }
}

From source file:fr.paris.lutece.plugins.workflow.modules.alert.service.daemon.AlertDaemon.java

/**
 * Daemon's treatment method//from  www  . j a v  a  2 s  .c  om
 */
public void run() {
    StringBuilder sbLog = new StringBuilder();
    ITaskConfigService configService = SpringContextService.getBean(AlertConstants.BEAN_ALERT_CONFIG_SERVICE);
    IAlertService alertService = SpringContextService.getBean(AlertService.BEAN_SERVICE);

    for (Alert alert : alertService.findAll()) {
        Record record = alertService.getRecord(alert);
        TaskAlertConfig config = configService.findByPrimaryKey(alert.getIdTask());

        Locale locale = I18nService.getDefaultLocale();

        if (record != null && config != null) {
            if (alertService.isRecordStateValid(config, record, locale)) {
                Long lDate = alert.getDateReference().getTime();

                if (lDate != null) {
                    int nNbDaysToDate = config.getNbDaysToDate();

                    Calendar calendar = new GregorianCalendar();
                    calendar.setTimeInMillis(lDate);
                    calendar.add(Calendar.DATE, nNbDaysToDate);

                    Calendar calendarToday = new GregorianCalendar();

                    if (calendar.before(calendarToday)) {
                        sbLog.append("\n-Running alert (ID record : " + record.getIdRecord() + ", ID history : "
                                + alert.getIdResourceHistory() + ", ID task : " + alert.getIdTask() + ")");
                        alertService.doChangeRecordState(config, record.getIdRecord(), alert);
                    }
                }
            }
        } else {
            // If the record is null or the config is null, we remove the alert
            alertService.removeByHistory(alert.getIdResourceHistory(), alert.getIdTask());
        }
    }

    if (StringUtils.isBlank(sbLog.toString())) {
        sbLog.append("\nNo alert to run.");
    }

    setLastRunLogs(sbLog.toString());
}

From source file:gov.utah.dts.det.ccl.model.FacilityTest.java

@Test
public void testGetActiveExemptions() {
    Date now = DateUtils.truncate(new Date(), Calendar.DATE);
    Facility f1 = new Facility();

    //an empty list should be returned when there are no exemptions
    assertTrue(f1.getActiveExemptions().isEmpty());

    Exemption e1 = new Exemption();
    e1.setStartDate(DateUtils.addDays(now, -60));
    e1.setExpirationDate(DateUtils.addDays(now, -30));
    f1.addExemption(e1);//from  w  w  w .jav  a  2 s. co m
    assertTrue(f1.getActiveLicenses().isEmpty());

    Exemption e2 = new Exemption();
    e2.setStartDate(DateUtils.addDays(now, -30));
    e2.setExpirationDate(DateUtils.addDays(now, 30));
    f1.addExemption(e2);
    assertTrue(f1.getActiveExemptions().size() == 1);
    assertEquals(f1.getActiveExemptions().get(0), e2);
}

From source file:org.openmrs.module.kenyaemr.calculation.library.mchms.HivTestedAtEnrollmentCalculationTest.java

/**
 * @see org.openmrs.module.kenyaemr.calculation.library.mchms.HivTestedAtEnrollmentCalculation#evaluate(java.util.Collection, java.util.Map, org.openmrs.calculation.patient.PatientCalculationContext)
 * @verifies determine whether MCH-MS patients had a known HIV status at enrollment
 *//*  w ww.ja v  a 2s.  c o  m*/
@Test
public void evaluate_shouldDetermineWhetherPatientHadKnownHivStatusAtEnrollment() throws Exception {

    // Get the MCH-MS program, enrollment encounter type and enrollment form
    Program mchmsProgram = MetadataUtils.existing(Program.class, MchMetadata._Program.MCHMS);
    EncounterType enrollmentEncounterType = MetadataUtils.existing(EncounterType.class,
            MchMetadata._EncounterType.MCHMS_ENROLLMENT);
    Form enrollmentForm = MetadataUtils.existing(Form.class, MchMetadata._Form.MCHMS_ENROLLMENT);

    //Enroll  #2, #6, #7 and #8 into MCH-MS
    TestUtils.enrollInProgram(TestUtils.getPatient(2), mchmsProgram, new Date());
    for (int i = 6; i <= 8; i++) {
        TestUtils.enrollInProgram(TestUtils.getPatient(i), mchmsProgram, new Date());
    }

    //Get the HIV Status and the HIV Test Date concepts
    Concept hivStatus = Dictionary.getConcept(Dictionary.HIV_STATUS);
    Concept hivTestDate = Dictionary.getConcept(Dictionary.DATE_OF_HIV_DIAGNOSIS);

    //Prepare enrollment date and also different dates when HIV test was done (a week before enrollment and a week after enrollment)
    Calendar enrollmentDate = Calendar.getInstance();
    Calendar oneWeekBeforeEnrollment = Calendar.getInstance();
    oneWeekBeforeEnrollment.add(Calendar.DATE, -7);
    Calendar oneWeekAfterEnrollment = Calendar.getInstance();
    oneWeekAfterEnrollment.add(Calendar.DATE, 7);

    //Create enrollment encounter for Pat#2 indicating HIV status 'Not Tested' known before enrollment
    Obs[] encounterObss2 = {
            TestUtils.saveObs(TestUtils.getPatient(2), hivStatus,
                    Dictionary.getConcept(Dictionary.NOT_HIV_TESTED), new Date()),
            TestUtils.saveObs(TestUtils.getPatient(2), hivTestDate, oneWeekBeforeEnrollment.getTime(),
                    new Date()) };
    TestUtils.saveEncounter(TestUtils.getPatient(2), enrollmentEncounterType, enrollmentForm, new Date(),
            encounterObss2);

    //Create enrollment encounter for Pat#6 indicating HIV status +ve known before enrollment
    Obs[] encounterObss6 = {
            TestUtils.saveObs(TestUtils.getPatient(6), hivStatus, Dictionary.getConcept(Dictionary.POSITIVE),
                    new Date()),
            TestUtils.saveObs(TestUtils.getPatient(6), hivTestDate, oneWeekBeforeEnrollment.getTime(),
                    new Date()) };
    TestUtils.saveEncounter(TestUtils.getPatient(6), enrollmentEncounterType, enrollmentForm, new Date(),
            encounterObss6);

    //Create enrollment encounter for Pat#7 indicating HIV status +ve known at enrollment
    Obs[] encounterObss7 = {
            TestUtils.saveObs(TestUtils.getPatient(7), hivStatus, Dictionary.getConcept(Dictionary.POSITIVE),
                    new Date()),
            TestUtils.saveObs(TestUtils.getPatient(7), hivTestDate, enrollmentDate.getTime(), new Date()) };
    TestUtils.saveEncounter(TestUtils.getPatient(7), enrollmentEncounterType, enrollmentForm, new Date(),
            encounterObss7);

    //Create enrollment encounter for Pat#8 indicating HIV status +ve known after enrollment
    Obs[] encounterObss8 = {
            TestUtils.saveObs(TestUtils.getPatient(8), hivStatus, Dictionary.getConcept(Dictionary.POSITIVE),
                    new Date()),
            TestUtils.saveObs(TestUtils.getPatient(8), hivTestDate, oneWeekAfterEnrollment.getTime(),
                    new Date()) };
    TestUtils.saveEncounter(TestUtils.getPatient(8), enrollmentEncounterType, enrollmentForm, new Date(),
            encounterObss8);

    Context.flushSession();

    List<Integer> ptIds = Arrays.asList(2, 6, 7, 8);

    //Run HivTestedAtEnrollmentCalculation with these test patients
    CalculationResultMap resultMap = Context.getService(PatientCalculationService.class).evaluate(ptIds,
            new HivTestedAtEnrollmentCalculation());

    Assert.assertFalse((Boolean) resultMap.get(2).getValue()); //HIV status not known
    Assert.assertTrue((Boolean) resultMap.get(6).getValue()); //HIV status known before enrollment
    Assert.assertTrue((Boolean) resultMap.get(7).getValue()); //HIV status known at enrollment
    Assert.assertFalse((Boolean) resultMap.get(8).getValue()); //HIV status known after enrollment
}

From source file:org.tdmx.lib.control.service.LockServiceRepositoryUnitTest.java

@Test
public void testAquireLock() throws Exception {
    String holderIdentitifier = UUID.randomUUID().toString();

    assertTrue(service.acquireLock(lockName, holderIdentitifier));

    String holderIdentitifier2 = UUID.randomUUID().toString();

    assertFalse(service.acquireLock(lockName, holderIdentitifier2));

    service.releaseLock(lockName, holderIdentitifier, null);

    assertTrue(service.acquireLock(lockName, holderIdentitifier2));

    Calendar futureDate = Calendar.getInstance();
    futureDate.add(Calendar.DATE, 1);

    service.releaseLock(lockName, holderIdentitifier2, futureDate.getTime());

    // cannot get lock because of time locking
    assertFalse(service.acquireLock(lockName, holderIdentitifier));

    // release for some time in the past
    Calendar pastDate = Calendar.getInstance();
    pastDate.add(Calendar.DATE, -1);
    service.releaseLock(lockName, holderIdentitifier2, pastDate.getTime());

    assertTrue(service.acquireLock(lockName, holderIdentitifier));
}

From source file:org.openmrs.module.accessmonitor.web.controller.AccessMonitorVisitController.java

@RequestMapping(value = "/module/accessmonitor/visit", method = RequestMethod.GET)
public void person(ModelMap model, HttpServletRequest request) {

    //        ((OrderAccessService) Context.getService(OrderAccessService.class)).generateData();
    //        ((VisitAccessService) Context.getService(VisitAccessService.class)).generateData();
    //        ((PersonAccessService) Context.getService(PersonAccessService.class)).generateData();
    offset = 0;/*ww w . j a va2  s.c  o m*/
    // parse them to Date, null is acceptabl
    DateFormat format = new SimpleDateFormat("MM/dd/yyyy");
    // Get the from date and to date
    Date to = null;
    Date from = null;
    try {
        from = format.parse(request.getParameter("datepickerFrom"));
    } catch (Exception e) {
        //System.out.println("======From Date Empty=======");
    }
    try {
        to = format.parse(request.getParameter("datepickerTo"));
    } catch (Exception e) {
        //System.out.println("======To Date Empty=======");
    }

    // get all the records in the date range
    visitAccessData = ((VisitAccessService) Context.getService(VisitAccessService.class))
            .getVisitAccessesByAccessDateOrderByPatientId(from, to);
    if (visitAccessData == null) {
        visitAccessData = new ArrayList<VisitServiceAccess>();
    }

    // get date for small graph
    Date toSmall = to;
    Date fromSmall = null;
    Calendar calendar = Calendar.getInstance();
    calendar.add(Calendar.DATE, 1);
    if (toSmall == null) {
        toSmall = calendar.getTime();
    } else {
        calendar.setTime(toSmall);
    }
    calendar.add(Calendar.DATE, -DAYNUM);
    fromSmall = calendar.getTime();

    List<String> dateStrings = new ArrayList<String>();
    for (int i = 0; i < DAYNUM; i++) {
        if (i == DAYNUM - 1) {
            dateStrings.add(format.format(toSmall));
        } else if (i == 0) {
            dateStrings.add(format.format(fromSmall));
        } else {
            dateStrings.add("");
        }
    }

    ArrayList<ArrayList<Integer>> tooltip = new ArrayList<ArrayList<Integer>>();
    tooltip.add(new ArrayList<Integer>());
    for (int j = 0; j < SHOWNUM + 1; j++) {
        tooltip.get(0).add(1000 + j);
    }
    for (int i = 1; i < DAYNUM + 1; i++) {
        tooltip.add(new ArrayList<Integer>());
        tooltip.get(i).add(i);
        for (int j = 0; j < SHOWNUM; j++) {
            tooltip.get(i).add(0);
        }
    }

    ArrayList<String> patientIds = new ArrayList<String>();
    ArrayList<Integer> patientCounts = new ArrayList<Integer>();
    for (VisitServiceAccess va : visitAccessData) {
        // data for big graph
        String idString = (va.getPatientId() == null) ? "No ID" : va.getPatientId().toString();
        int index = patientIds.indexOf(idString);
        if (index < 0) {
            if (patientIds.size() >= SHOWNUM)
                break;
            patientIds.add(idString);
            patientCounts.add(1);
            index = patientIds.size() - 1;//index = patientIds.indexOf(idString);
        } else {
            patientCounts.set(index, patientCounts.get(index) + 1);
        }
        // data for small graph
        if (va.getAccessDate().after(fromSmall) && va.getAccessDate().before(toSmall)) {
            int index2 = (int) ((va.getAccessDate().getTime() - fromSmall.getTime()) / (1000 * 60 * 60 * 24));
            if (index2 < DAYNUM && index2 >= 0)
                tooltip.get(index2 + 1).set(index + 1, tooltip.get(index2 + 1).get(index + 1) + 1);
        }
    }
    String patientIdString = JSONValue.toJSONString(patientIds);
    String patientCountString = JSONValue.toJSONString(patientCounts);
    String dateSmallString = JSONValue.toJSONString(dateStrings);
    String tooltipdata = JSONValue.toJSONString(tooltip);
    model.addAttribute("patientIds", patientIdString);
    model.addAttribute("patientCounts", patientCountString);
    model.addAttribute("dateSmallString", dateSmallString);
    model.addAttribute("tooltipdata", tooltipdata);

    model.addAttribute("user", Context.getAuthenticatedUser());
    //        model.addAttribute("tables1", visitAccessData);
    //        model.addAttribute("dateSmall", dateStrings);
    model.addAttribute("currentoffset", String.valueOf(offset));
}

From source file:org.callistasoftware.netcare.core.job.SystemAlarmJob.java

@Scheduled(fixedRate = 43200000)
public void compressPdlLog() {
    log.info("======== COMPRESS PDL LOG JOB STARTED =========");
    Calendar fromCal = Calendar.getInstance();
    fromCal.add(Calendar.DATE, -1);
    Calendar toCal = Calendar.getInstance();
    toCal.add(Calendar.MINUTE, -2);

    log.info("select log records between" + fromCal.getTime() + " : " + toCal.getTime());

    // Order By hsaId, civiId, action, healthPlanName,  date
    final List<PdlLogEntity> entities = pdlLogRepository.findByDateBetween(fromCal.getTime(), toCal.getTime());
    log.debug("remove duplicate pdlLog number of candidates:" + entities.size());
    List<PdlLogEntity> duplicates = new ArrayList<PdlLogEntity>();
    PdlLogEntity lastPdlLog = null;//  w w  w. j ava2s .c  o m
    for (final PdlLogEntity pdlLog : entities) {
        if (lastPdlLog == null) {
            lastPdlLog = pdlLog;
            continue;
        }

        if (pdlLog.getHsaId().equals(lastPdlLog.getHsaId())
                && pdlLog.getCivicId().equals(lastPdlLog.getCivicId())
                && pdlLog.getAction().equals(lastPdlLog.getAction())
                && pdlLog.getHealtPlanName().equals(lastPdlLog.getHealtPlanName())) {
            duplicates.add(pdlLog);
            log.debug("remove duplicate pdlLog:" + pdlLog.getId());
        }
        lastPdlLog = pdlLog;
    }
    log.debug("remove duplicate pdlLog number of items:" + duplicates.size());
    pdlLogRepository.delete(duplicates);
    log.info("======== COMPRESS PDL LOG JOB COMPLETED =========");
}

From source file:userinterface.EnvironmentRole.PollutionCheckJPanel.java

public void populateTable() {
    int rowCount = tableCarOwners.getRowCount();
    DefaultTableModel model = (DefaultTableModel) tableCarOwners.getModel();
    for (int i = rowCount - 1; i >= 0; i--) {
        model.removeRow(i);/*  w  ww .  j  a  v  a  2 s . c o  m*/
    }
    for (WorkRequest request : environmentOrganization.getWorkQueue().getWorkRequestList()) {
        if (account == request.getReceiver() || request.getReceiver() == null) {
            Object[] row = new Object[5];
            row[0] = ((EnvironmentWorkRequest) request).getCarListing().getCarOwner().getName();
            row[1] = ((EnvironmentWorkRequest) request).getCarListing();

            String expectedPattern = "MM/dd/yyyy";
            SimpleDateFormat formatter = new SimpleDateFormat(expectedPattern);
            Date userInput = ((EnvironmentWorkRequest) request).getCarListing().getLastPollution(); // MM/DD/YYYY
            if (userInput != null) {
                String date = formatter.format(userInput);
                row[2] = date;
            } else {
                row[2] = null;
            }

            row[3] = ((EnvironmentWorkRequest) request);

            SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
            Calendar c = Calendar.getInstance();
            c.setTime(((EnvironmentWorkRequest) request).getCarListing().getLastPollution()); // Now use today date.
            c.add(Calendar.DATE, 90); // Adding 90 days
            String output = sdf.format(c.getTime());
            //                System.out.println(output);

            row[4] = output;

            model.addRow(row);
        }
    }

}

From source file:gov.va.isaac.gui.listview.operations.UscrsExportOperation.java

/**
 * Pass in a Date and the function will return a Date, but at the start of that day.
 * @param Date the day and time you would like to modify
 * @return Date and time at the beginning of the day
 *//* w w w  .  j a  v a  2 s .  c  om*/
public static Date getStartOfDay(Date date) {
    return DateUtils.truncate(date, Calendar.DATE);
}