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.example.android.myargmenuplanner.data.LoadMenu.java

@Override
protected String[] doInBackground(String... params) {

    Uri mUri = MenuEntry.CONTENT_URI;

    Cursor mCursor = mContext.getContentResolver().query(mUri, null, null, null, null);

    if (mCursor.getCount() == 0) {

        int shift = 0;
        DateFormat df = new SimpleDateFormat("yyyy-MM-dd");
        Calendar cal = Calendar.getInstance();
        String sDate = df.format(cal.getTime());
        int dayofweek = cal.get(Calendar.DAY_OF_WEEK);

        Log.i(LOG_TAG, "Init Date: " + date);
        Vector<ContentValues> cVVector = new Vector<ContentValues>(14 - dayofweek);

        for (int i = dayofweek; i <= 14; i++) {

            ContentValues values = new ContentValues();

            values.put(MenuEntry.COLUMN_DATE, sDate);
            values.put(MenuEntry.COLUMN_LUNCH, "Empty");
            values.put(MenuEntry.COLUMN_ID_LUNCH, 0);
            values.put(MenuEntry.COLUMN_DINNER, "Empty");
            values.put(MenuEntry.COLUMN_ID_DINNER, 0);

            cVVector.add(values);/*from ww w  .  j  a va  2s  .  c  o  m*/

            cal.add(Calendar.DATE, 1);
            sDate = df.format(cal.getTime());
            //            Log.i(LOG_TAG, "Day of the week: "+cal.get(Calendar.DAY_OF_WEEK));
            //            Log.i(LOG_TAG, "Date: "+date);

        }

        int inserted = 0;

        //            // add to database
        Log.i(LOG_TAG, "Creando registros en base de datos. Tabla Menu ");

        if (cVVector.size() > 0) {
            ContentValues[] cvArray = new ContentValues[cVVector.size()];
            cVVector.toArray(cvArray);

            inserted = mContext.getContentResolver().bulkInsert(MenuEntry.CONTENT_URI, cvArray);
            Log.i(LOG_TAG, "Registros nuevos creados en Tabla Menu: " + inserted);
        }

    } else { //ya tengo registros, tengo que fijarme las fechas

        DateFormat df = new SimpleDateFormat("yyyy-MM-dd");
        Calendar cal = Calendar.getInstance();
        String dateNow = df.format(cal.getTime());
        int dayofweek = cal.get(Calendar.DAY_OF_WEEK);
        String date = "";
        String week = "";
        while (mCursor.moveToNext()) {

            date = mCursor.getString(1);

            if (dateNow.equals(date)) {

            }
        }

    }

    return null;
}

From source file:csns.model.academics.Assignment.java

public Assignment() {
    dueDate = Calendar.getInstance();
    dueDate.add(Calendar.DATE, 7);
    dueDate.set(Calendar.HOUR_OF_DAY, 23);
    dueDate.set(Calendar.MINUTE, 59);
    dueDate.set(Calendar.SECOND, 59);
    dueDate.set(Calendar.MILLISECOND, 0);

    submissions = new ArrayList<Submission>();
    fileExtensionSet = new HashSet<String>();
    availableAfterDueDate = true;/*from  w  ww .jav a2  s.  c  o m*/
    deleted = false;
}

From source file:org.openmhealth.shim.fatsecret.FatsecretShim.java

@Override
public ShimDataResponse getData(ShimDataRequest shimDataRequest) throws ShimException {

    long numToSkip = 0;
    long numToReturn = 3;

    Calendar cal = Calendar.getInstance();
    cal.set(2014, Calendar.AUGUST, 1);
    Date endDate = new Date(cal.getTimeInMillis());
    cal.add(Calendar.DATE, -1);
    Date startDate = new Date(cal.getTimeInMillis());

    DateTime startTime = new DateTime(startDate.getTime());
    DateTime endTime = new DateTime(endDate.getTime());

    MutableDateTime epoch = new MutableDateTime();
    epoch.setDate(0);/*from   w w  w  .  j  av a  2  s  .c o  m*/

    int days = 16283; //Days.daysBetween(epoch, new DateTime()).getDays() - 1;

    String endPoint = "food_entries.get";

    String accessToken = shimDataRequest.getAccessParameters().getAccessToken();
    String tokenSecret = shimDataRequest.getAccessParameters().getTokenSecret();

    URL url = signUrl(DATA_URL + "?date=" + days + "&format=json&method=" + endPoint, accessToken, tokenSecret,
            null);
    System.out.println("Signed URL is: \n\n" + url);

    // Fetch and decode the JSON data.
    ObjectMapper objectMapper = new ObjectMapper();
    JsonNode jsonData;

    HttpGet get = new HttpGet(url.toString());
    HttpResponse response;
    try {
        response = httpClient.execute(get);
        HttpEntity responseEntity = response.getEntity();
        jsonData = objectMapper.readTree(responseEntity.getContent());
        return ShimDataResponse.result(FatsecretShim.SHIM_KEY, jsonData);

    } catch (IOException e) {
        throw new ShimException("Could not fetch data", e);
    } finally {
        get.releaseConnection();
    }
}

From source file:org.motechproject.server.event.MessageProgramNumStateChangeTest.java

@Override
protected void setUp() throws Exception {
    Calendar calendar = Calendar.getInstance();
    calendar.setTime(new Date());
    calendar.add(Calendar.MONTH, -1); // 1 month in past

    obs1 = calendar.getTime();/*from ww w  .j  a v  a2  s .co m*/

    calendar.add(Calendar.DATE, 6 * 7 + 1); // 6 weeks and 1 day
    obs2 = calendar.getTime();

    calendar.add(Calendar.DATE, 4 * 7 + 2); // 4 weeks and 2 days
    obs3 = calendar.getTime();

    calendar.add(Calendar.DATE, 4 * 7 + 3); // 4 weeks and 3 days
    obs4 = calendar.getTime();

    calendar.add(Calendar.DATE, 4 * 7 + 4); // 4 weeks and 4 days
    obs5 = calendar.getTime();

    patientId = 1;

    enrollment = new MessageProgramEnrollment();
    enrollment.setPersonId(patientId);

    ctx = new ClassPathXmlApplicationContext(
            new String[] { "test-common-program-beans.xml", "polio-program-test-context.xml" });
    polioProgram = (MessageProgram) ctx.getBean("polioProgram");

    polioState1 = (MessageProgramState) ctx.getBean("polioState1");
    polioState2 = (MessageProgramState) ctx.getBean("polioState2");
    polioState3 = (MessageProgramState) ctx.getBean("polioState3");
    polioState4 = (MessageProgramState) ctx.getBean("polioState4");
    polioState5 = (MessageProgramState) ctx.getBean("polioState5");

    polioConceptName = polioState1.getConceptName();

    polioConceptValue = polioState1.getConceptValue();

    // EasyMock setup in Spring config
    registrarBean = (RegistrarBean) ctx.getBean("registrarBean");
}

From source file:com.yukthi.validators.GreaterThanEqualsValidator.java

@Override
public boolean isValid(Object bean, Object fieldValue) {
    if (bean == null) {
        return true;
    }/*from   ww  w  .  ja  v  a2s  .  co  m*/

    //fetch other field value
    Object otherValue = null;

    try {
        otherValue = PropertyUtils.getProperty(bean, greaterThanField);
    } catch (IllegalAccessException | InvocationTargetException | NoSuchMethodException ex) {
        throw new IllegalStateException("Invalid/inaccessible property \"" + greaterThanField
                + "\" specified with matchWith validator in bean: " + bean.getClass().getName());
    }

    //ensure other field value is present and is of same type
    if (fieldValue == null || otherValue == null || !fieldValue.getClass().equals(otherValue.getClass())) {
        return true;
    }

    //number comparison
    if (otherValue instanceof Number) {
        return (((Number) fieldValue).doubleValue() >= ((Number) otherValue).doubleValue());
    }

    //date comparison
    if (otherValue instanceof Date) {
        Date dateValue = DateUtils.truncate((Date) fieldValue, Calendar.DATE);
        Date otherDateValue = DateUtils.truncate((Date) otherValue, Calendar.DATE);

        return (dateValue.compareTo(otherDateValue) >= 0);
    }

    return true;
}

From source file:com.sap.csc.poc.ems.persistence.initial.entitlement.SoftwareLicenseEntitlementHeaderDataInitializer.java

private Calendar createRandomCalendar(int day) {
    Calendar date = Calendar.getInstance();
    date.add(Calendar.DATE, day);
    return date;
}

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

/**
 * @see LateEnrollmentCalculation#evaluate(java.util.Collection, java.util.Map, org.openmrs.calculation.patient.PatientCalculationContext)
 * @verifies determine whether MCH-MS patients enrolled at gestation greater than 28 weeks
 *///from  w  ww  .jav  a  2  s. c  om
@Test
public void evaluate_shouldDetermineWhetherPatientsEnrolledLate() 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 #6 and #7 into MCH-MS
    TestUtils.enrollInProgram(TestUtils.getPatient(6), mchmsProgram, new Date());
    TestUtils.enrollInProgram(TestUtils.getPatient(7), mchmsProgram, new Date());

    //Get the LMP concept
    Concept lmp = Dictionary.getConcept(Dictionary.LAST_MONTHLY_PERIOD);

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

    //Create enrollment encounter for Pat#6 indicating HIV status + and LMP 10 weeks ago
    Obs[] encounterObss6 = {
            TestUtils.saveObs(TestUtils.getPatient(6), lmp, tenWeeksAgo.getTime(), new Date()) };
    TestUtils.saveEncounter(TestUtils.getPatient(6), enrollmentEncounterType, enrollmentForm, new Date(),
            encounterObss6);

    //Create enrollment encounter for Pat#7 indicating HIV status + and LMP 30 weeks ago
    Obs[] encounterObss7 = {
            TestUtils.saveObs(TestUtils.getPatient(7), lmp, twentyWeeksAgo.getTime(), new Date()) };
    TestUtils.saveEncounter(TestUtils.getPatient(7), enrollmentEncounterType, enrollmentForm, new Date(),
            encounterObss7);

    Context.flushSession();

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

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

    Assert.assertFalse((Boolean) resultMap.get(6).getValue()); //Enrolled at 10 weeks gestation - not late enrollment
    Assert.assertTrue((Boolean) resultMap.get(7).getValue()); //Enrolled at 30 weeks gestation - late enrollment
    Assert.assertFalse((Boolean) resultMap.get(2).getValue()); // Not in MCH-MS Program
    Assert.assertFalse((Boolean) resultMap.get(999).getValue()); // Voided patient
}

From source file:com.weavers.duqhan.business.impl.AdminServiceImpl.java

private Date nextUpdate() {
    Calendar calendar = Calendar.getInstance(); // set token validity
    calendar.add(Calendar.DATE, 1);
    return calendar.getTime();
}

From source file:fr.cph.stock.external.YahooExternalDataAccess.java

@Override
public final List<Company> getCompaniesData(final List<String> yahooIds) throws YahooException {
    List<Company> companies = new ArrayList<Company>();

    String requestQuotes = "select * from yahoo.finance.quotes where symbol in (" + getFormattedList(yahooIds)
            + ")";
    Yahoo yahoo = new Yahoo(requestQuotes);
    JSONObject json = yahoo.getJSONObject();
    JSONArray jsonResults = getJSONArrayFromJSONObject(json);
    for (int j = 0; j < jsonResults.size(); j++) {
        JSONObject jsonCompany = jsonResults.getJSONObject(j);
        Company company = new Company();
        company.setYahooId(jsonCompany.optString("symbol"));
        company.setManual(false);/*from   www .  j  a va2 s . c o  m*/
        if (jsonCompany.optString("StockExchange").equals("null")) {
            company = getCompanyInfo(company);
            if (company.getSector() != null && company.getIndustry() != null
                    && company.getMarketCapitalization() != null) {
                company.setRealTime(false);
                company.setMarket(guessMarket(company.getYahooId()));
                company.setCurrency(Market.getCurrency(company.getMarket()));
                Calendar cal = Calendar.getInstance();
                cal.add(Calendar.DATE, -5);
                try {
                    List<Company> temp = getCompanyDataHistory(company.getYahooId(), cal.getTime(), null);
                    company.setQuote(temp.get(0).getQuote());
                } catch (YahooException e) {
                    LOG.info(e.getMessage(), e);
                }
                companies.add(company);
            } else {
                throw new YahooUnknownTickerException(
                        jsonCompany.optString("symbol") + YahooUnknownTickerException.TOCKEN_UNKNOWN);
            }
        } else {
            company.setName(WordUtils.capitalizeFully(jsonCompany.optString("Name")));
            company.setMarket(Market.getMarket(jsonCompany.optString("StockExchange").toUpperCase()));

            company.setCurrency(Market.getCurrency(company.getMarket()));
            if (!jsonCompany.optString("DividendYield").equals("null")) {
                company.setYield(Double.valueOf(jsonCompany.optString("DividendYield")));
            }
            company.setQuote(Double.valueOf(jsonCompany.optString("LastTradePriceOnly")));
            String marketCap = jsonCompany.optString("MarketCapitalization");
            if (marketCap != null && !marketCap.equals("null") && !marketCap.equals("")) {
                company.setMarketCapitalization(marketCap);
            }
            Double previousClose = jsonCompany.optDouble("PreviousClose");
            if (previousClose != null && !previousClose.isNaN()) {
                company.setYesterdayClose(previousClose);
            } else {
                company.setYesterdayClose(0.0);
            }
            company.setChangeInPercent(jsonCompany.optString("ChangeinPercent"));
            Double yearLow = jsonCompany.optDouble("YearLow");
            if (!yearLow.isNaN()) {
                company.setYearLow(yearLow);
            }
            Double yearHigh = jsonCompany.optDouble("YearHigh");
            if (!yearHigh.isNaN()) {
                company.setYearHigh(yearHigh);
            }
            company.setRealTime(true);
            company.setFund(false);
            companies.add(company);
        }
    }
    return companies;
}

From source file:com.davidmogar.alsa.services.schedule.internal.ScheduleManagerServiceImpl.java

@Override
public List<ScheduleDto> findAll(RouteDto routeDto, Date date) {
    List<ScheduleDto> schedules = new ArrayList<>();
    Place originPlace = placeDataService.findOne(routeDto.getOrigin().getId());
    Place destinationPlace = placeDataService.findOne(routeDto.getDestination().getId());

    if (originPlace != null && destinationPlace != null) {
        Route route = routeDataService.findByOriginAndDestination(originPlace, destinationPlace);

        if (route != null) {

            /* Get tomorrow date */
            Calendar calendar = Calendar.getInstance();
            calendar.setTime(date);// w  w w  . jav a 2 s  .  c o m
            calendar.add(Calendar.DATE, 1);

            schedules.addAll(StreamSupport.stream(scheduleDataService
                    .findByRouteAndDateBetween(route, date, calendar.getTime()).spliterator(), false)
                    .map(ScheduleDto::new).collect(Collectors.toList()));
        }
    }

    return schedules;
}