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:org.motechproject.server.service.OPVScheduleTest.java

public void testSkipExpired() {
    Date date = new Date();

    Calendar calendar = Calendar.getInstance();
    calendar.setTime(date);/* w w  w  .  j  av a2s. c  om*/
    calendar.add(Calendar.DATE, -28); // age is 4 weeks

    Patient patient = new Patient();
    patient.setBirthdate(calendar.getTime());
    patient.setDateCreated(calendar.getTime());
    Capture<Date> minDateCapture = new Capture<Date>();
    Capture<Date> dueDateCapture = new Capture<Date>();
    Capture<Date> lateDateCapture = new Capture<Date>();
    Capture<Date> maxDateCapture = new Capture<Date>();

    List<Obs> obsList = new ArrayList<Obs>();
    List<ExpectedObs> expectedObsList = new ArrayList<ExpectedObs>();

    expect(registrarBean.getObs(patient, opvSchedule.getConceptName(), opvSchedule.getValueConceptName(),
            patient.getBirthdate())).andReturn(obsList);
    expect(registrarBean.getExpectedObs(patient, opvSchedule.getName())).andReturn(expectedObsList);
    expect(registrarBean.createExpectedObs(eq(patient), eq(opvSchedule.getConceptName()),
            eq(opvSchedule.getValueConceptName()), eq(opv1Event.getNumber()), capture(minDateCapture),
            capture(dueDateCapture), capture(lateDateCapture), capture(maxDateCapture), eq(opv1Event.getName()),
            eq(opvSchedule.getName()))).andReturn(new ExpectedObs());
    calendar.set(2010, 03, 10);
    expect(registrarBean.getChildRegistrationDate()).andReturn(calendar.getTime());

    calendar.set(2011, 03, 10);
    Encounter encounter = new Encounter();
    encounter.setEncounterDatetime(calendar.getTime());
    expect(registrarBean.getEncounters(patient, MotechConstants.ENCOUNTER_TYPE_PATIENTREGVISIT,
            patient.getBirthdate())).andReturn(Arrays.asList(encounter));

    replay(registrarBean);

    opvSchedule.updateSchedule(patient, date);

    verify(registrarBean);

    Date dueDate = dueDateCapture.getValue();
    Date lateDate = lateDateCapture.getValue();

    assertNotNull("Due date is null", dueDate);
    assertNotNull("Late date is null", lateDate);
    assertTrue("Late date is not after due date", lateDate.after(dueDate));

}

From source file:com.github.xlstosql.SqlGenerator.java

private void readTables() {
    result = new StringBuilder();
    try {//from   ww  w.  j a  v  a 2s  . c  o  m
        for (String fileName : files) {
            Workbook workbook = Workbook.getWorkbook(new File(fileName));
            List<String> sheetNames = new ArrayList<String>();
            for (Sheet sheet : workbook.getSheets()) {
                sheetNames.add(sheet.getName());
                headers = sheet.getRow(0);
                for (int indexRow = 1; indexRow < sheet.getRows(); indexRow += 1) {
                    sheetName = sheet.getName();
                    appendHeaders();
                    Cell[] datas = sheet.getRow(indexRow);
                    if (datas != null && datas.length > 0) {
                        result.append(translateValue(0, cellToString(datas[0])));
                    }
                    for (int indexCell = 1; indexCell < headers.length; indexCell += 1) {
                        if (isValidDictHeader(headers[indexCell].getContents())) {
                            result.append(", " + translateValue(indexCell, cellToString(datas[indexCell])));
                        }
                    }
                    if (isDict()) {
                        Calendar today = Calendar.getInstance();
                        Calendar from = (Calendar) today.clone();
                        Calendar to = (Calendar) today.clone();
                        from.add(Calendar.DATE, -1000);
                        to.add(Calendar.DATE, 1000);
                        result.append(", '" + sheetName.substring(5) + "', 1, " + toSqlFormat(from) + ", "
                                + toSqlFormat(to) + ", " + toSqlFormat(today));
                    }
                    result.append(")\n");
                }
            }
            workbook.close();
            IOUtils.write(result.toString(), new FileOutputStream(outSql), "cp1251");
            getLog().log(Level.INFO, "read " + fileName.replaceFirst(".*/(.*)", "$1") + " - " + sheetNames);
        }
    } catch (Exception ex) {
        getLog().log(Level.WARNING, ex.getMessage(), ex);
    }
}

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

/**
 * @see NotOnArtCalculation#evaluate(java.util.Collection, java.util.Map, org.openmrs.calculation.patient.PatientCalculationContext)
 * @verifies determine whether MCH-MS patients have been tested for HIV
 *//*from ww w . j a  v a2  s. c  o  m*/
@Test
public void evaluate_shouldDetermineWhetherPatientsAreNotOnArt() 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 concept, the LMP concept and the ART use in Pregnanacy concepts
    Concept hivStatus = Dictionary.getConcept(Dictionary.HIV_STATUS);
    Concept lmp = Dictionary.getConcept(Dictionary.LAST_MONTHLY_PERIOD);
    Concept artUse = Dictionary.getConcept(Dictionary.ANTIRETROVIRAL_USE_IN_PREGNANCY);

    //Prepare times since last LMP (10 weeks ago and 20 weeks ago)
    Calendar tenWeeksAgo = Calendar.getInstance();
    tenWeeksAgo.add(Calendar.DATE, -70);
    Calendar twentyWeeksAgo = Calendar.getInstance();
    twentyWeeksAgo.add(Calendar.DATE, -140);

    //Create enrollment encounter for Pat#2 indicating HIV status - and LMP 20 weeks ago
    Obs[] encounterObss2 = {
            TestUtils.saveObs(TestUtils.getPatient(2), hivStatus, Dictionary.getConcept(Dictionary.NEGATIVE),
                    new Date()),
            TestUtils.saveObs(TestUtils.getPatient(2), lmp, twentyWeeksAgo.getTime(), new Date()) };
    TestUtils.saveEncounter(TestUtils.getPatient(2), enrollmentEncounterType, enrollmentForm, new Date(),
            encounterObss2);
    //Create ART use in Pregnancy obs for Pat#2 indicating NOT_APPLICABLE
    TestUtils.saveObs(TestUtils.getPatient(2), artUse, Dictionary.getConcept(Dictionary.NOT_APPLICABLE),
            new Date());

    //Create enrollment encounter for Pat#6 indicating HIV status + and LMP 10 weeks ago
    Obs[] encounterObss6 = {
            TestUtils.saveObs(TestUtils.getPatient(6), hivStatus, Dictionary.getConcept(Dictionary.POSITIVE),
                    new Date()),
            TestUtils.saveObs(TestUtils.getPatient(6), lmp, tenWeeksAgo.getTime(), new Date()) };
    TestUtils.saveEncounter(TestUtils.getPatient(6), enrollmentEncounterType, enrollmentForm, new Date(),
            encounterObss6);
    //Create ART use in Pregnancy obs for Pat#6 indicating NOT_APPLICABLE
    TestUtils.saveObs(TestUtils.getPatient(6), artUse, Dictionary.getConcept(Dictionary.NOT_APPLICABLE),
            new Date());

    //Create enrollment encounter for Pat#7 indicating HIV status + and LMP 20 weeks ago
    Obs[] encounterObss7 = {
            TestUtils.saveObs(TestUtils.getPatient(7), hivStatus, Dictionary.getConcept(Dictionary.POSITIVE),
                    new Date()),
            TestUtils.saveObs(TestUtils.getPatient(7), lmp, twentyWeeksAgo.getTime(), new Date()) };
    TestUtils.saveEncounter(TestUtils.getPatient(7), enrollmentEncounterType, enrollmentForm, new Date(),
            encounterObss7);
    //Create ART use in Pregnancy obs for Pat#8 indicating NOT_APPLICABLE
    TestUtils.saveObs(TestUtils.getPatient(7), artUse, Dictionary.getConcept(Dictionary.NOT_APPLICABLE),
            new Date());

    //Create enroollment encounter for Pat#8 indicating HIV status + and LMP 20 weeks ago
    Obs[] encounterObss8 = {
            TestUtils.saveObs(TestUtils.getPatient(8), hivStatus, Dictionary.getConcept(Dictionary.POSITIVE),
                    new Date()),
            TestUtils.saveObs(TestUtils.getPatient(8), lmp, twentyWeeksAgo.getTime(), new Date()) };
    TestUtils.saveEncounter(TestUtils.getPatient(8), enrollmentEncounterType, enrollmentForm, new Date(),
            encounterObss8);
    //Create ART use in Pregnancy obs for Pat#8  indicating MOTHER_ON_PROPHYLAXIS
    TestUtils.saveObs(TestUtils.getPatient(8), artUse, Dictionary.getConcept(Dictionary.MOTHER_ON_PROPHYLAXIS),
            new Date());

    Context.flushSession();

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

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

    Assert.assertFalse((Boolean) resultMap.get(2).getValue()); //Not HIV+ - need not be on ART
    Assert.assertFalse((Boolean) resultMap.get(6).getValue()); //HIV+ and not on ART but gestation less than 14 weeks - need not be on ART
    Assert.assertTrue((Boolean) resultMap.get(7).getValue()); //HIV+ and not on ART and gestation is greater than 14 weeks - needs to be on ART
    Assert.assertFalse((Boolean) resultMap.get(8).getValue()); //HIV+ and on ART and gestation is greater than 14 weeks - need not to be on ART
}

From source file:hu.petabyte.redflags.web.svc.SecuritySvc.java

private String sendEmailConfirmation(Account a, String urlFormat, String labelPrefix, Locale loc) {
    String token = UUID.randomUUID().toString();
    Calendar c = Calendar.getInstance();
    c.setTime(new Date());
    c.add(Calendar.DATE, 1);
    a.setRememberToken(token);//from w w  w.ja va2  s . c om
    a.setRememberTokenExpiresAt(c.getTime());
    accounts.save(a);

    String to = a.getEmailAddress();
    String subject = String
            .format(msg.getMessage(String.format("%s.%s", labelPrefix, "mail.subject"), null, loc));
    String text = String.format(msg.getMessage(String.format("%s.%s", labelPrefix, "mail"), null, loc),
            a.getName(), String.format(urlFormat, a.getId(), token));

    if (email.send(to, subject, text)) {
        return String.format("%s.%s", labelPrefix, "sent");
    } else {
        return String.format("%s.%s", labelPrefix, "failed");
    }
}

From source file:com.hzq.project.cronJob.CartUtil.java

public void startGrab() throws Exception {
    String token = getToken();/*  w ww. jav a  2  s .co  m*/
    logger.warn("getToken: {}", token);
    Calendar calendar = Calendar.getInstance();
    calendar.setTime(new Date());
    calendar.add(Calendar.DATE, -1);
    Date grabDate = calendar.getTime();
    String url = DATA_URL_TEST;
    if (isProd)
        url = DATA_URL_PROD;
    sendAndSave(token, grabDate, url);
}

From source file:av1.model.Processo.java

public void gerarNumeroProcesso() {

    Calendar calendario = Calendar.getInstance();
    this.numeroProcesso = calendario.get(Calendar.YEAR) + "" + calendario.get(Calendar.MONTH + 1) + ""
            + calendario.get(Calendar.DATE) + "" + calendario.get(Calendar.HOUR_OF_DAY) + ""
            + calendario.get(Calendar.MINUTE) + "" + calendario.get(Calendar.SECOND) + ""
            + this.fornecedor.getCNPJ();

    this.numeroProcesso = this.numeroProcesso.replaceAll("[^a-zZ-Z1-9 ]", "");

}

From source file:com.jennifer.ui.util.scale.TimeScale.java

public JSONArray realTicks(String type, int step) {
    long start = this.minLong();
    long end = this.maxLong();

    JSONArray times = new JSONArray();

    Calendar c = Calendar.getInstance();

    Date date = TimeUtil.get(start);
    Date realStart = null;/* www. j  a v a  2  s .c o m*/

    c.setTime(date);
    if (Time.YEARS.equals(type)) {
        c.set(c.get(Calendar.YEAR), 1, 1, 0, 0, 0);
    } else if (Time.MONTHS.equals(type)) {
        c.set(c.get(Calendar.YEAR), c.get(Calendar.MONTH), 1, 0, 0, 0);
    } else if (Time.DAYS.equals(type)) {
        c.set(c.get(Calendar.YEAR), c.get(Calendar.MONTH), c.get(Calendar.DATE), 0, 0, 0);
    } else if (Time.HOURS.equals(type)) {
        c.set(c.get(Calendar.YEAR), c.get(Calendar.MONTH), c.get(Calendar.DATE), c.get(Calendar.HOUR_OF_DAY), 0,
                0);
    } else if (Time.MINUTES.equals(type)) {
        c.set(c.get(Calendar.YEAR), c.get(Calendar.MONTH), c.get(Calendar.DATE), c.get(Calendar.HOUR_OF_DAY),
                c.get(Calendar.MINUTE), 0);
    } else if (Time.SECONDS.equals(type)) {
        c.set(c.get(Calendar.YEAR), c.get(Calendar.MONTH), c.get(Calendar.DATE), c.get(Calendar.HOUR_OF_DAY),
                c.get(Calendar.MINUTE), c.get(Calendar.SECOND));
    }

    realStart = c.getTime();

    long start2 = realStart.getTime();
    while (start2 < end) {
        times.put(start2);

        start2 = TimeUtil.add(start2, type, step);
    }

    double first = this.get(times.getLong(1));
    double second = this.get(times.getLong(2));

    _rangeBand = second - first;

    return times;
}

From source file:Servlet3.java

@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    try {//from  w  w  w .  j ava2  s  . c o  m
        System.out.println("inside servlet");
        String a = request.getParameter("countryf");
        String c = request.getParameter("submit");
        String b = request.getParameter("paramf");

        String CurentUID = request.getParameter("UIDvalue2f");
        String URLRequest = request.getRequestURL().append('?').append(request.getQueryString()).toString();
        Calendar cal = Calendar.getInstance();
        cal.add(Calendar.DATE, 1);
        SimpleDateFormat format1 = new SimpleDateFormat("EEE MMM dd hh:mm:ss yyyy");
        String date1 = cal.getTime().toString();

        System.out.println("inside servlet");

        Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
        Connection con = DriverManager.getConnection("jdbc:odbc:server");

        // To Insert data to UserActivity table for Recent Activities Tab
        Statement sthistoryinsert3 = con.createStatement();
        String insertstring = "Insert into UserActivity values('" + CurentUID + "','" + date1
                + "','Future Data Forecast','" + a + "','" + b + "','" + URLRequest + "')";
        sthistoryinsert3.executeUpdate(insertstring);
        sthistoryinsert3.close();
        System.out.println("\n Step 1");
        Statement st = con.createStatement();
        XYSeriesCollection dataset = new XYSeriesCollection();
        XYSeries series = new XYSeries(b);

        String query = "SELECT [2000],[2012] FROM country where CountryName='" + a + "' AND SeriesName='" + b
                + "'";
        System.out.println(query);
        ResultSet rs = st.executeQuery(query);
        if (rs == null)
            System.out.println("\n no rows ");
        else
            System.out.println("Rows present ");
        rs.next();

        Double start = Double.parseDouble(rs.getString(1));
        Double end = Double.parseDouble(rs.getString(2));
        Double period = 13.0;
        Double growth = Math.pow((end / start), (1 / period)) - 1;
        System.out.println("growth percentage =" + growth);
        rs.close();
        String query2 = "select [2011],[2012] from country where CountryName='" + a + "' AND SeriesName='" + b
                + "'";
        rs = st.executeQuery(query2);
        rs.next();
        series.add(2011, Double.parseDouble(rs.getString(1)));
        Double second = Double.parseDouble(rs.getString(2));
        series.add(2012, second);

        Double growthvalue = second + (second * growth);

        series.add(2013, growthvalue);
        for (int i = 2014; i <= 2016; i++) {
            System.out.println("actual growth value = " + growthvalue);
            series.add((i++), (growthvalue + growthvalue * growth));
            growthvalue = growthvalue + growthvalue * growth;
        }
        rs.close();
        dataset.addSeries(series);
        DecimalFormat format_2Places = new DecimalFormat("0.00");
        growth = growth * 100;
        growth = Double.valueOf(format_2Places.format(growth));
        JFreeChart chart = ChartFactory.createXYLineChart(
                "Energy forecasting for " + a + " based on " + b + " with growth value estimated at " + growth
                        + "% ",
                "Year", "Energy consumed in millions", dataset, PlotOrientation.VERTICAL, true, true, false);
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        chart.setBackgroundPaint(Color.white);
        final XYPlot plot = chart.getXYPlot();
        plot.setBackgroundPaint(Color.white);
        plot.setDomainGridlinesVisible(true);
        plot.setRangeGridlinesVisible(true);
        plot.setDomainGridlinePaint(Color.black);
        plot.setRangeGridlinePaint(Color.black);

        final XYLineAndShapeRenderer renderer = new XYLineAndShapeRenderer();
        renderer.setSeriesLinesVisible(2, false);
        renderer.setSeriesShapesVisible(2, false);
        plot.setRenderer(renderer);
        // To insert colored Pie Chart into the PDF file using
        // iText now   
        if (c.equals("View Graph in Browser")) {
            ChartUtilities.writeChartAsPNG(bos, chart, 700, 500);
            response.setContentType("image/png");
            OutputStream out = new BufferedOutputStream(response.getOutputStream());
            out.write(bos.toByteArray());
            out.flush();
            out.close();
        }

        else {
            int width = 640; /* Width of our chart */
            int height = 480; /* Height of our chart */
            Document PieChart = new Document(new com.itextpdf.text.Rectangle(width, height));
            java.util.Date date = new java.util.Date();
            String chartname = "My_Colored_Chart" + date.getTime() + ".pdf";
            PdfWriter writer = PdfWriter.getInstance(PieChart, new FileOutputStream(chartname));
            PieChart.open();

            PieChart.addTitle("Pie-Chart");
            PieChart.addAuthor("MUurugappan");

            PdfContentByte Add_Chart_Content = writer.getDirectContent();
            PdfTemplate template_Chart_Holder = Add_Chart_Content.createTemplate(width, height);
            Graphics2D Graphics_Chart = template_Chart_Holder.createGraphics(width, height,
                    new DefaultFontMapper());
            Rectangle2D Chart_Region = new Rectangle2D.Double(0, 0, 540, 380);
            chart.draw(Graphics_Chart, Chart_Region);
            Graphics_Chart.dispose();
            Add_Chart_Content.addTemplate(template_Chart_Holder, 0, 0);
            PieChart.close();

            PdfReader reader = new PdfReader(chartname);
            PdfStamper stamper = null;
            try {
                stamper = new PdfStamper(reader, bos);
            } catch (DocumentException e) {
                e.printStackTrace();
            }
            try {
                stamper.close();
            } catch (DocumentException e) {

                e.printStackTrace();
            }

            // set response headers to view PDF
            response.setHeader("Expires", "0");
            response.setHeader("Cache-Control", "must-revalidate, post-check=0, pre-check=0");
            response.setHeader("Pragma", "public");
            response.setContentType("application/pdf");
            response.setContentLength(bos.size());

            OutputStream os = response.getOutputStream();
            bos.writeTo(os);
            os.flush();
            os.close();
        }
    }

    catch (Exception i) {
        i.printStackTrace();
    }

}

From source file:Main.java

/**
 * Get the date for the given values.//  w  w  w. ja v  a  2s  .co  m
 *
 * @param day
 *            The day.
 * @param month
 *            The month.
 * @param year
 *            The year.
 * @return The date represented by the given values.
 */
private static Date getDate(int day, int month, int year) {
    Calendar cal = Calendar.getInstance();
    cal.set(Calendar.YEAR, year);
    cal.set(Calendar.MONTH, month);
    cal.set(Calendar.DATE, day);
    return cal.getTime();
}

From source file:com.cse3310.phms.ui.fragments.AppointmentScreenFragment.java

private void updateCalendarPickerView() {
    int year = mSelectedMonth.get(Calendar.YEAR);
    int month = mSelectedMonth.get(Calendar.MONTH);
    int numDays = mSelectedMonth.getActualMaximum(Calendar.DATE) + 1;

    // get the first day of the month
    Calendar minDate = Calendar.getInstance();
    minDate.set(Calendar.YEAR, year);
    minDate.set(Calendar.MONTH, month);
    minDate.set(Calendar.DATE, 1);

    // get the last day of the month
    Calendar maxDate = Calendar.getInstance();
    maxDate.set(Calendar.YEAR, year);
    maxDate.set(Calendar.MONTH, month);
    maxDate.set(Calendar.DATE, numDays);

    // set range of calendar and highlight current date
    mCalendarPickerView.init(minDate.getTime(), maxDate.getTime());
    mCalendarPickerView.setOnDateSelectedListener(this);

    // get all dates that have an appointment from the current selected month and year
    Set<Date> dates = new HashSet<Date>();
    for (Appointment appointment : mUser.getAppointments()) {
        Date date = new Date(appointment.getTime());
        if (isSameMonthAndYear(mSelectedMonth, date))
            dates.add(date);/* ww w .j a v  a 2 s  .  c  o  m*/
    }

    // highlight those dates that have a least one appointment
    mCalendarPickerView.highlightDates(dates);
}