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:fxts.stations.trader.ui.dialogs.ADatePage.java

/**
 * Returns ending date//  w w  w.j a va2 s.co m
 *
 * @return
 */
public String getEndDate() {
    Calendar instance = Calendar.getInstance();
    instance.setTime(mCalendarComboEnd.getDate());
    boolean date = instance.get(Calendar.DATE) == Calendar.getInstance().get(Calendar.DATE);
    boolean month = instance.get(Calendar.MONTH) == Calendar.getInstance().get(Calendar.MONTH);
    boolean year = instance.get(Calendar.YEAR) == Calendar.getInstance().get(Calendar.YEAR);
    if (date && month && year) {
        return "now";
    } else {
        return mDateFormat.format(mCalendarComboEnd.getDate());
    }
}

From source file:com.acmeair.loader.FlightLoader.java

public void loadFlights() throws Exception {
    InputStream csvInputStream = FlightLoader.class.getResourceAsStream("/mileage.csv");

    LineNumberReader lnr = new LineNumberReader(new InputStreamReader(csvInputStream));
    String line1 = lnr.readLine();
    StringTokenizer st = new StringTokenizer(line1, ",");
    ArrayList<AirportCodeMapping> airports = new ArrayList<AirportCodeMapping>();

    // read the first line which are airport names
    while (st.hasMoreTokens()) {
        AirportCodeMapping acm = new AirportCodeMapping();
        acm.setAirportName(st.nextToken());
        airports.add(acm);/*  w  w  w.  j  a v a 2s.c om*/
    }
    // read the second line which contains matching airport codes for the first line
    String line2 = lnr.readLine();
    st = new StringTokenizer(line2, ",");
    int ii = 0;
    while (st.hasMoreTokens()) {
        String airportCode = st.nextToken();
        airports.get(ii).setAirportCode(airportCode);
        ii++;
    }
    // read the other lines which are of format:
    // airport name, aiport code, distance from this airport to whatever airport is in the column from lines one and two
    String line;
    int flightNumber = 0;
    while (true) {
        line = lnr.readLine();
        if (line == null || line.trim().equals("")) {
            break;
        }
        st = new StringTokenizer(line, ",");
        String airportName = st.nextToken();
        String airportCode = st.nextToken();
        if (!alreadyInCollection(airportCode, airports)) {
            AirportCodeMapping acm = new AirportCodeMapping();
            acm.setAirportName(airportName);
            acm.setAirportCode(airportCode);
            airports.add(acm);
        }
        int indexIntoTopLine = 0;
        while (st.hasMoreTokens()) {
            String milesString = st.nextToken();
            if (milesString.equals("NA")) {
                indexIntoTopLine++;
                continue;
            }
            int miles = Integer.parseInt(milesString);
            String toAirport = airports.get(indexIntoTopLine).getAirportCode();
            String flightId = "AA" + flightNumber;
            FlightSegment flightSeg = new FlightSegment(flightId, airportCode, toAirport, miles);
            flightService.storeFlightSegment(flightSeg);
            Date now = new Date();
            for (int daysFromNow = 0; daysFromNow < MAX_FLIGHTS_PER_SEGMENT; daysFromNow++) {
                Calendar c = Calendar.getInstance();
                c.setTime(now);
                c.set(Calendar.HOUR_OF_DAY, 0);
                c.set(Calendar.MINUTE, 0);
                c.set(Calendar.SECOND, 0);
                c.set(Calendar.MILLISECOND, 0);
                c.add(Calendar.DATE, daysFromNow);
                Date departureTime = c.getTime();
                Date arrivalTime = getArrivalTime(departureTime, miles);
                flightService.createNewFlight(flightId, departureTime, arrivalTime, new BigDecimal(500),
                        new BigDecimal(200), 10, 200, "B747");

            }
            flightNumber++;
            indexIntoTopLine++;
        }
    }

    for (int jj = 0; jj < airports.size(); jj++) {
        flightService.storeAirportMapping(airports.get(jj));
    }
    lnr.close();
}

From source file:net.naijatek.myalumni.util.quartz.BirthdayWishJob.java

/**
 * <p>//from w  ww .ja va2  s. c om
 * Called by the <code>{@link org.quartz.Scheduler}</code> when a
 * <code>{@link org.quartz.Trigger}</code> fires that is associated with
 * the <code>Job</code>.
 * </p>
 * 
 * @throws JobExecutionException
 *             if there is an exception while executing the job.
 */
public void execute(JobExecutionContext context) throws JobExecutionException {

    try {
        WebApplicationContext wac = WebApplicationContextUtils.getWebApplicationContext(getServletContext());
        IMemberService memService = (IMemberService) wac.getBean(BaseConstants.SERVICE_MEMBER_LOOKUP);
        ISystemConfigService sysConfigService = (ISystemConfigService) wac
                .getBean(BaseConstants.SERVICE_SYSTEM_CONFIG);

        SystemConfigVO sysConfigVO = sysConfigService.getSystemConfig();

        // This job simply prints out its job name and the
        // date and time that it is running
        //String jobName = context.getJobDetail().getFullName();
        //logger.info("===> BirthdayWishJob says: " + jobName + " executing at " + new Date());

        Calendar now = new GregorianCalendar();
        int today = now.get(java.util.Calendar.DATE);

        // get the list of birthday people
        List<MemberVO> members = new ArrayList<MemberVO>();
        members = memService.getTodayBirthdayMembers(
                StringUtil.convertToAlphaMonth(now.get(Calendar.MONTH) + 1), String.valueOf(today));
        System.out.println("Getting memebrs...");
        for (MemberVO memberVO : members) {
            if (memberVO.getEmail() != null && memberVO.getEmail().length() > 0) {
                //SendMailUtil.sendBirthdayWish(memberVO, sysConfigVO);
                System.out.println("Sent birthday wishes to " + memberVO.getFullName());
            }
        }

    } catch (Exception e) {
        logger.fatal("Schedular failed. " + e.getMessage());
        e.printStackTrace();
    }

}

From source file:org.openmrs.module.kenyaemr.calculation.library.hiv.LostToFollowUpCalculationTest.java

/**
 * @see LostToFollowUpCalculation#evaluate(java.util.Collection, java.util.Map, org.openmrs.calculation.patient.PatientCalculationContext)
 * @verifies determine whether patients are lost to follow up
 *///from   w ww.  ja  v a  2s .  co  m
@Test
public void evaluate_shouldDetermineWhetherPatientsAreLostToFollowUp() throws Exception {
    Program hivProgram = MetadataUtils.existing(Program.class, HivMetadata._Program.HIV);
    Concept returnVisitDate = Dictionary.getConcept(Dictionary.RETURN_VISIT_DATE);
    Concept reasonForDiscontinuation = Dictionary.getConcept(Dictionary.REASON_FOR_PROGRAM_DISCONTINUATION);
    Concept dead = Dictionary.getConcept(Dictionary.DIED);
    Concept transferout = Dictionary.getConcept(Dictionary.TRANSFERRED_OUT);

    // Enroll patients #6, #7, #8 in the HIV Program
    TestUtils.enrollInProgram(TestUtils.getPatient(6), hivProgram, TestUtils.date(2011, 1, 1));
    TestUtils.enrollInProgram(TestUtils.getPatient(7), hivProgram, TestUtils.date(2011, 1, 1));
    TestUtils.enrollInProgram(TestUtils.getPatient(8), hivProgram, TestUtils.date(2011, 1, 1));

    //give patient 6 and 7 return date
    Obs[] returnDate6 = { TestUtils.saveObs(TestUtils.getPatient(6), returnVisitDate,
            TestUtils.date(2011, 4, 1), TestUtils.date(2011, 1, 1)) };
    Obs[] returnDate7 = { TestUtils.saveObs(TestUtils.getPatient(7), returnVisitDate,
            TestUtils.date(2011, 4, 1), TestUtils.date(2011, 1, 1)) };
    Obs[] discontinuation6 = { TestUtils.saveObs(TestUtils.getPatient(6), reasonForDiscontinuation, dead,
            TestUtils.date(2011, 1, 1)) };
    Obs[] discontinuation7 = { TestUtils.saveObs(TestUtils.getPatient(7), reasonForDiscontinuation, dead,
            TestUtils.date(2011, 1, 1)) };
    Obs[] discontinuation8 = { TestUtils.saveObs(TestUtils.getPatient(8), reasonForDiscontinuation, transferout,
            TestUtils.date(2011, 1, 1)) };

    // Give patient #7 a scheduled encounter 200 days ago
    Calendar calendar = Calendar.getInstance();
    calendar.add(Calendar.DATE, -200);
    EncounterType scheduledEncType = Context.getEncounterService().getEncounterType("Scheduled");
    TestUtils.saveEncounter(TestUtils.getPatient(7), scheduledEncType, calendar.getTime(), returnDate7);

    // Give patient #8 a scheduled encounter 10 days ago
    calendar = Calendar.getInstance();
    calendar.add(Calendar.DATE, -10);
    TestUtils.saveEncounter(TestUtils.getPatient(8), scheduledEncType, calendar.getTime());

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

    CalculationResultMap resultMap = new LostToFollowUpCalculation().evaluate(ptIds, null,
            Context.getService(PatientCalculationService.class).createCalculationContext());
    Assert.assertTrue((Boolean) resultMap.get(6).getValue()); // patient in HIV program and no encounters
    Assert.assertTrue((Boolean) resultMap.get(7).getValue()); // patient in HIV program and no encounter in last X days
    Assert.assertFalse((Boolean) resultMap.get(8).getValue()); // patient in HIV program and is a transfer out
    Assert.assertFalse((Boolean) resultMap.get(999).getValue()); // patient not in HIV Program
}

From source file:org.alfresco.test.util.ContentAspectsTests.java

@Test
public void addDocComplianceableAspect() {
    Calendar calendar = Calendar.getInstance();
    calendar.add(Calendar.DATE, 3);
    Date removeAfter = calendar.getTime();
    contentAspect.addComplianceable(userName, password, siteName, plainDoc, removeAfter);
    List<Property<?>> properties = contentAspect.getProperties(userName, password, siteName, plainDoc);
    Assert.assertTrue(contentAspect.getPropertyValue(properties, "cm:removeAfter")
            .contains(new SimpleDateFormat(DATE_FORMAT).format(removeAfter)));
}

From source file:org.openmrs.module.pihmalawi.reporting.definition.dataset.evaluator.EncounterBreakdownDataSetEvaluator.java

/**
 * @throws EvaluationException /*w  w  w. j  av a 2s .c  o  m*/
 * @see DataSetEvaluator#evaluate(DataSetDefinition, EvaluationContext)
 */
public DataSet evaluate(DataSetDefinition dataSetDefinition, EvaluationContext context)
        throws EvaluationException {

    context = ObjectUtil.nvl(context, new EvaluationContext());
    MapDataSet data = new MapDataSet(dataSetDefinition, context);

    EncounterBreakdownDataSetDefinition dsd = (EncounterBreakdownDataSetDefinition) dataSetDefinition;

    // Construct the encounter filters to iterate across
    Map<String, List<EncounterType>> encounterTypeFilters = new LinkedHashMap<String, List<EncounterType>>();
    List<EncounterType> otherEncounterTypes = Context.getEncounterService().getAllEncounterTypes();
    for (int encTypeNum = 1; encTypeNum <= dsd.getTypes().size(); encTypeNum++) {
        EncounterType encounterType = dsd.getTypes().get(encTypeNum - 1);
        encounterTypeFilters.put("enc" + encTypeNum, Arrays.asList(encounterType));
        otherEncounterTypes.remove(encounterType);
    }
    encounterTypeFilters.put("otherenc", otherEncounterTypes);

    // Construct the user and location filters to iterate across
    Map<String, List<User>> userFilters = new LinkedHashMap<String, List<User>>();
    Map<String, List<Location>> locationFilters = new LinkedHashMap<String, List<Location>>();

    if (dsd.getGrouping() == EncounterBreakdownDataSetDefinition.Grouping.User) {

        // Determine what users to iterate across.  Default to top 10, and "other"
        List<User> mostFrequentUsers = getUsersOrderedByNumEncounters(
                DateUtil.adjustDate(dsd.getEndDate(), -7 * dsd.getNumberOfWeeks(), Calendar.DATE),
                dsd.getEndDate(), context);
        List<User> otherUsers = Context.getUserService().getAllUsers();

        for (int userNum = 1; userNum <= mostFrequentUsers.size() && userNum <= 10; userNum++) {
            User user = mostFrequentUsers.get(userNum - 1);
            String userKey = "user" + userNum;
            userFilters.put(userKey, Arrays.asList(user));
            otherUsers.remove(user);
            data.addData(new DataSetColumn(userKey + "name", userKey + "name", String.class),
                    user.getUsername());
        }
        userFilters.put("userother", otherUsers);
    } else {

        List<Location> locations = metadata.getSystemLocations();
        List<Location> otherLocations = Context.getLocationService().getAllLocations();
        for (int locationNum = 1; locationNum <= locations.size(); locationNum++) {
            Location location = locations.get(locationNum - 1);
            String locationKey = "loc" + locationNum;
            List<Location> locList = metadata.getAllLocations(location);
            locationFilters.put(locationKey, locList);
            otherLocations.removeAll(locList);
            data.addData(new DataSetColumn(locationKey + "name", locationKey + "name", String.class),
                    location.getName());
        }
        locationFilters.put("locother", otherLocations);

    }

    // Now, iterate across the product of all of these and add them to the data set

    Date startDate, endDate = null;

    for (int weekNum = 0; weekNum < dsd.getNumberOfWeeks(); weekNum++) {

        endDate = (endDate == null ? dsd.getEndDate() : DateUtil.adjustDate(endDate, -7, Calendar.DATE));
        startDate = DateUtil.adjustDate(endDate, -6, Calendar.DATE);

        for (String encounterTypeKey : encounterTypeFilters.keySet()) {

            List<EncounterType> encounterTypes = encounterTypeFilters.get(encounterTypeKey);

            for (String userKey : userFilters.keySet()) {
                List<User> users = userFilters.get(userKey);
                String key = userKey + encounterTypeKey + "ago" + weekNum;
                addData(data, key, startDate, endDate, encounterTypes, users, null, context);
            }

            for (String locationKey : locationFilters.keySet()) {
                List<Location> locations = locationFilters.get(locationKey);
                String key = locationKey + encounterTypeKey + "ago" + weekNum;
                addData(data, key, startDate, endDate, encounterTypes, null, locations, context);
            }
        }
    }

    return data;
}

From source file:dao.Graficos.java

public JFreeChart GraficoBarras(List<CarCapContas> contas, String titulo, FiltroData filtro, String estilo,
        Date dataInicial, Date dataFinal) {

    ArrayList<String> tipoFiltragem = new ArrayList();
    DefaultCategoryDataset dataset = new DefaultCategoryDataset();

    int tipo = 0;
    // 1 - diario // 2 - mensal// 3 - anual

    switch (filtro) {

    case Diario:/* w  ww.j  av  a 2s .  c  om*/

        int intervaloDatas = new utils.Utils().diasEntreDatas(Utils.formatData(dataInicial),
                Utils.formatData(dataFinal));

        Calendar c = Calendar.getInstance();

        c.setTime(dataInicial);

        if (estilo.equals("full")) {

            for (int i = 0; i <= intervaloDatas; i++) {

                tipoFiltragem.add(Utils.formatData(c.getTime()));

                c.add(Calendar.DATE, 1);
            }

        } else if (estilo.equals("small")) {

            for (int i = 0; i <= intervaloDatas; i++) {

                String[] dia = Utils.formatData(c.getTime()).split("/");

                tipoFiltragem.add(dia[0]);

                c.set(Calendar.DATE, +1);
            }

        }

        tipo = 1;

        dataset = montarDataSet(tipo, tipoFiltragem, contas, dataInicial, dataFinal);

        break;

    case Mensal:

        if (estilo.equals("full")) {

            tipoFiltragem.add("Janeiro");
            tipoFiltragem.add("Fevereiro");
            tipoFiltragem.add("Maro");
            tipoFiltragem.add("Abril");
            tipoFiltragem.add("Maio");
            tipoFiltragem.add("Junho");
            tipoFiltragem.add("Julho");
            tipoFiltragem.add("Agosto");
            tipoFiltragem.add("Setembro");
            tipoFiltragem.add("Outubro");
            tipoFiltragem.add("Novembro");
            tipoFiltragem.add("Dezembro");

        } else if (estilo.equals("small")) {

            tipoFiltragem.add("Jan");
            tipoFiltragem.add("Fev");
            tipoFiltragem.add("Mar");
            tipoFiltragem.add("Abr");
            tipoFiltragem.add("Mai");
            tipoFiltragem.add("Jun");
            tipoFiltragem.add("Jul");
            tipoFiltragem.add("Ago");
            tipoFiltragem.add("Set");
            tipoFiltragem.add("Out");
            tipoFiltragem.add("Nov");
            tipoFiltragem.add("Dez");

        }

        tipo = 2;

        dataset = montarDataSet(tipo, tipoFiltragem, contas, null, null);

        break;

    case Anual:

        Calendar c2 = Calendar.getInstance();

        //seta ano atual
        tipoFiltragem.add(String.valueOf(c2.get(Calendar.YEAR)));

        // seta prximos 5 anos
        for (int i = 1; i < 6; i++) {

            c2.add(Calendar.YEAR, 1);

            tipoFiltragem.add(String.valueOf(c2.get(Calendar.YEAR)));

        }

        tipo = 3;
        break;
    }

    JFreeChart barChart = ChartFactory.createBarChart(titulo, "Ms", "Valor total", dataset,
            PlotOrientation.VERTICAL, true, true, false);

    return barChart;

}

From source file:org.vietspider.server.handler.cms.metas.IndexSearchHandler.java

public String handle(final HttpRequest request, final HttpResponse response, final HttpContext context,
        String... params) throws Exception {
    String pattern = params[1];/*from  w  w  w .  jav a 2s.  c o  m*/
    int idx = pattern.indexOf('=');
    if (idx < 0 || idx >= pattern.length() - 1) {
        throw new IndexOutOfBoundsException("Incorrect parammeter");
    }

    String search = URLDecoder.decode(pattern.substring(idx + 1), "UTF-8");

    pattern = search;

    MetaList metas = new MetaList();
    metas.setAction("SEARCH");
    metas.setCurrentPage(Integer.parseInt(params[0]));

    String[][] parameters = ParameterParser.getParameters(params[1]);

    /*SearchQuery query = null;
    if(parameters.length > 0) {
      query = new SearchQuery(parameters[0][1]);
    //      for(int i = 1; i < parameters.length; i++) {
    //        if("region".equalsIgnoreCase(parameters[i][0])) {
    //          query.setRegion(parameters[i][1]);
    //        }
    //      }
    } else {
      throw new IndexOutOfBoundsException("Incorrect parammeter");
    }*/

    ArticleSearchQuery query = new ArticleSearchQuery();
    for (int i = 0; i < parameters.length; i++) {
        if (parameters[i][0].charAt(0) == '?') {
            parameters[i][0] = parameters[i][0].substring(1);
        }
        //      System.out.println(parameters[i][0] + " : "+ parameters[i][1]);
        if (parameters[i][0].equals("text")) {
            query.setPattern(parameters[i][1]);
        } else if (parameters[i][0].equals("source")) {
            query.setSource(parameters[i][1]);
        } else if (parameters[i][0].equals("dtstart")) {
            parameters[i][1] = parameters[i][1].replace('.', '/');
            try {
                SimpleDateFormat dateFormat = CalendarUtils.getDateFormat();
                Date date = dateFormat.parse(parameters[i][1]);
                Calendar calendar = Calendar.getInstance();
                calendar.setTime(date);
                calendar.set(Calendar.HOUR, 0);
                calendar.set(Calendar.MINUTE, 0);
                calendar.set(Calendar.SECOND, 0);
                query.setIndexFrom(calendar.getTimeInMillis());
            } catch (Exception e) {
                LogService.getInstance().setMessage(e, e.toString());
            }
        } else if (parameters[i][0].equals("dtend")) {
            parameters[i][1] = parameters[i][1].replace('.', '/');
            try {
                SimpleDateFormat dateFormat = CalendarUtils.getDateFormat();
                Date date = dateFormat.parse(parameters[i][1]);
                Calendar calendar = Calendar.getInstance();
                calendar.setTime(date);
                calendar.set(Calendar.HOUR, 0);
                calendar.set(Calendar.MINUTE, 0);
                calendar.set(Calendar.SECOND, 0);
                calendar.set(Calendar.DATE, calendar.get(Calendar.DATE) + 1);
                query.setIndexTo(calendar.getTimeInMillis());
            } catch (Exception e) {
                LogService.getInstance().setMessage(e, e.toString());
            }
        }
    }

    if (Application.LICENSE != Install.PERSONAL) {
        //      ArticleSearchQuery query = new ArticleSearchQuery(parameters[0][1]);
        query.setHighlightStart("<b style=\"color: black; background-color: rgb(255, 255, 102);\">");
        query.setHighlightEnd("</b>");
        ArticleIndexStorage.getInstance().search(metas, query);
    }

    //    System.out.println("thay co " + metas.getData().size());

    //    System.out.println(parameters[0][1]);

    //    File tempFolder = UtilFile.getFolder("content/temp/search/");
    //    ContentSearcher2 searcher = new ContentSearcher2(ContentSearcher2.SIMPLE, tempFolder);
    //    HighlightBuilder highlighter = new HighlightBuilder(query.getPattern().toLowerCase());
    //    highlighter.setHighlightTag("<b style=\"color: black; background-color: rgb(255, 255, 102);\">", "</b>");
    //      query.setParser(new QueryParser());
    //    DefaultArticleHandler articleHandler2 = new DefaultArticleHandler(highlighter);
    //    searcher.search(metas, query, articleHandler2);
    //    ContentSearcher searcher = new ContentSearcher();
    //    searcher.search(metas, pattern);

    WebRM resources = new WebRM();
    StringBuilder builder = new StringBuilder(resources.getLabel("search"));
    metas.setTitle(builder.toString());
    metas.setUrl(params[1]);

    return write(request, response, context, metas, params);
}

From source file:com.discovery.darchrow.date.DateExtensionUtil.java

/**
 *  [yestoday,today]<br>/*w ww .j a v  a  2  s  .c  o m*/
 * 00:00 <br>
 * 00:00 <br>
 * sql/hql?,between ... and ...
 * 
 * <pre>
 *  :2012-10-16 22:46:42
 * 
 * return  {2012-10-15 00:00:00.000,2012-10-16 00:00:00.000}
 * </pre>
 * 
 * @return Date <br>
 *         00:00 <br>
 *         00:00
 * @since 1.0
 * @deprecated ??
 */
@Deprecated
public static Date[] getExtentYesterday() {
    Calendar calendar = CalendarUtil.resetCalendarByDay(new Date());
    Date today = calendar.getTime();
    calendar.add(Calendar.DATE, -1);
    Date yesterday = calendar.getTime();
    return new Date[] { yesterday, today };
}

From source file:cn.mypandora.util.MyDateUtils.java

/**
 * //from w w w  .  j av  a 2 s. c om
 *
 * @return
 */
public static String getNextMonthFirst() {
    Calendar cal = Calendar.getInstance();
    Calendar f = (Calendar) cal.clone();
    f.clear();
    // 
    // f.set(Calendar.YEAR, cal.get(Calendar.YEAR));
    // f.set(Calendar.MONTH, cal.get(Calendar.MONTH) + 1);
    // f.set(Calendar.DATE, 1);
    // or f.set(Calendar.DAY_OF_MONTH,cal.getActualMinimum(Calendar.DATE));
    // return DateFormatUtils.format(f, DATE_FORMAT);

    // 
    cal.set(Calendar.DATE, 1);// ?1?
    cal.add(Calendar.MONTH, +1);// ?1?
    return DateFormatUtils.format(cal, DATE_FORMAT);
}