Example usage for java.util Date getYear

List of usage examples for java.util Date getYear

Introduction

In this page you can find the example usage for java.util Date getYear.

Prototype

@Deprecated
public int getYear() 

Source Link

Document

Returns a value that is the result of subtracting 1900 from the year that contains or begins with the instant in time represented by this Date object, as interpreted in the local time zone.

Usage

From source file:dssat.WeatherFileSystem.java

public String WriteToFile(String wthFileName) {

    // prepare the file name from the organization name and the site index number and then write to that file
    String orgName = incache.get("Farm");
    String siteIndex = incache.get("SiteIndex");
    String finalOutputPath = readAttribute("DssatFolder");
    finalOutputPath = finalOutputPath + "\\" + readAttribute("Crop");

    File file = new File(finalOutputPath + dirseprator + wthFileName);

    String writeBuffer = null;//from w  w w  .ja v a 2  s  .  c  o  m

    PrintWriter pr = null;
    try {
        file.createNewFile();
        pr = new PrintWriter(file);
        writeBuffer = new String("*WEATHER : \n");
        pr.println(writeBuffer);
        writeBuffer = new String("@ INSI      LAT     LONG  ELEV   TAV   AMP REFHT WNDHT");
        pr.println(writeBuffer);

        double latitude = -34.23;
        double longitude = -34.23;
        double elevation = -99;
        double tavg = -99;
        double tamp = -99;
        double tmht = -99;
        double wmht = -99;

        writeBuffer = new String();
        //Empty 2 Char, Org 2 Char, Site 2Char, Space 1 Char, latitude 8Chars with 3 dec
        writeBuffer = String.format(
                "%.2s%.2s%.2s%.1s%8.3f%.1s%8.3f%.1s%5.0f%.1s%5.1f%.1s%5.1f%.1s%5.1f%.1s%5.1f", "  ", orgName,
                siteIndex, " ", latitude, " ", longitude, " ", elevation, " ", tavg, " ", tamp, " ", tmht, " ",
                wmht);
        pr.println(writeBuffer);

        int julianday = 56001;
        double solarrad = -99;
        double tmax = -99;
        double tmin = -99;
        double rain = -99;
        double dewp = -99;
        double wind = -99;
        double par = -99;

        writeBuffer = new String("@DATE  SRAD  TMAX  TMIN  RAIN  RHUM  WIND  TDEW  PAR");
        pr.println(writeBuffer);
        writeBuffer = new String();

        URL url = null;
        InputStream is = null;
        Integer plantingyear;
        if (incache.get("PlantingYear") != null) {
            plantingyear = Integer.parseInt(incache.get("PlantingYear"));
        } else {
            Date d = new Date();
            plantingyear = d.getYear() + 1900;
        }
        /*Bring the Weather details for last 10 Years and write the details to the WTH File. */
        try {

            String query = new String("SELECT%20*%20FROM%20FAWN_historic_daily_20140212%20"
                    + "WHERE%20(%20yyyy%20BETWEEN%20" + (plantingyear - 10) + "%20AND%20"
                    + plantingyear.toString() + ")" + "%20AND%20(%20LocId%20=%20"
                    + incache.get("StationLocationId") + ")" + "%20ORDER%20BY%20yyyy%20DESC%20");

            String urlStr = "http://abe.ufl.edu/bmpmodel/xmlread/rohit.php?sql=" + query;

            System.out.println("********************************");
            System.out.println(urlStr);

            //System.out.println(urlStr);
            URL uflconnection = new URL(urlStr);
            HttpURLConnection huc = (HttpURLConnection) uflconnection.openConnection();
            HttpURLConnection.setFollowRedirects(false);
            huc.setConnectTimeout(15 * 1000);
            huc.setRequestMethod("GET");
            huc.connect();
            InputStream input = huc.getInputStream();
            BufferedReader in = new BufferedReader(new InputStreamReader(input));
            String inputLine;

            while ((inputLine = in.readLine()) != null) {
                if (!(inputLine.startsWith("S") || inputLine.startsWith("s"))) {
                    String[] fields = inputLine.split(",");

                    int M = Integer.parseInt(fields[3]);
                    int D = Integer.parseInt(fields[4]);
                    int a = (14 - M) / 12;
                    int y = Integer.parseInt(fields[2]) + 4800 - a;
                    int m = M + 12 * a - 3;

                    long JD = D + (153 * m + 2) / 5 + 365 * y + y / 4 - y / 100 + y / 400 - 32045;

                    String tempDate = String.format("%05d",
                            Integer.parseInt(fields[2].substring(2)) * 1000 + Integer.parseInt(fields[5]));
                    String SRad;
                    if (fields[13].length() > 1) {
                        SRad = String.format("%.1f", Double.parseDouble(fields[13]));
                    } else {
                        SRad = "";
                    }
                    String TMax = String.format("%.1f", Double.parseDouble(fields[9]));
                    String TMin = String.format("%.1f", Double.parseDouble(fields[8]));
                    String RAIN = String.format("%.1f", Double.parseDouble(fields[12]));
                    String RHUM = String.format("%.1f", Double.parseDouble(fields[11]));
                    String WIND = String.format("%.1f", Double.parseDouble(fields[14]));
                    String TDEW = String.format("%.1f", Double.parseDouble(fields[10]));
                    String PAR = "";

                    String line = String.format("%5s %5s %5s %5s %5s %5s %5s %5s", tempDate, SRad, TMax, TMin,
                            RAIN, RHUM, WIND, TDEW);
                    pr.println(line);

                }
            }
            in.close();
            //System.out.println("Created teh connection successfully");

        } catch (MalformedURLException me) {
            me.printStackTrace();
            //return 21.4;
        } catch (Exception e) {
            e.printStackTrace();
        }
    } catch (Exception e) {
        e.printStackTrace();
    } finally {

        if (pr != null) {
            pr.close();
        }
    }

    // Here I need to read all the data from the controls and write the data to the files. 
    for (int i = 0; i < incache.size(); i++) {

    }
    return file.getAbsolutePath();
}

From source file:org.apache.carbondata.processing.merger.CarbonDataMergerUtil.java

/**
 * Method to check if the load dates are complied to the configured dates.
 *
 * @param segDate1/*from   w  w  w  .ja  va 2 s  .co m*/
 * @param segDate2
 * @return
 */
private static boolean isTwoDatesPresentInRequiredRange(Date segDate1, Date segDate2,
        long numberOfDaysAllowedToMerge) {
    if (segDate1 == null || segDate2 == null) {
        return false;
    }
    // take 1 st date add the configured days .
    Calendar cal1 = Calendar.getInstance();
    cal1.set(segDate1.getYear(), segDate1.getMonth(), segDate1.getDate());
    Calendar cal2 = Calendar.getInstance();
    cal2.set(segDate2.getYear(), segDate2.getMonth(), segDate2.getDate());

    long diff = cal2.getTimeInMillis() - cal1.getTimeInMillis();

    if ((diff / (24 * 60 * 60 * 1000)) < numberOfDaysAllowedToMerge) {
        return true;
    }
    return false;
}

From source file:org.yccheok.jstock.gui.news.StockNewsJFrame.java

private boolean isSameDay(Date date0, Date date1) {
    return date0.getDate() == date1.getDate() && date0.getMonth() == date1.getMonth()
            && date0.getYear() == date1.getYear();
}

From source file:org.apache.openjpa.persistence.kernel.TestProxies2.java

public void testDate() {
    OpenJPAEntityManager pm = getPM(true, true);
    startTx(pm);/*from w  ww .j ava  2  s .co m*/
    ProxiesPC pc = pm.find(ProxiesPC.class, _oid);
    Date date = pc.getDate();
    assertNotNull(date);

    // dates can lose precision, but make sure same day
    assertEquals(_date.getYear(), date.getYear());
    assertEquals(_date.getMonth(), date.getMonth());
    assertEquals(_date.getDate(), date.getDate());

    // make sure proxied
    assertTrue(!pm.isDirty(pc));
    date.setTime(System.currentTimeMillis() + 1000 * 60 * 60 * 24);
    assertTrue(pm.isDirty(pc));

    endTx(pm);
    assertEquals(date, pc.getDate());
    endEm(pm);
}

From source file:org.apache.openjpa.persistence.kernel.TestProxies2.java

public void testSQLDate() {
    OpenJPAEntityManager pm = getPM(true, true);
    startTx(pm);/* ww  w. ja  v  a 2 s . c o m*/
    ProxiesPC pc = pm.find(ProxiesPC.class, _oid);
    java.sql.Date date = pc.getSQLDate();
    assertNotNull(date);

    // dates can lose precision, but make sure same day
    assertEquals(_sqlDate.getYear(), date.getYear());
    assertEquals(_sqlDate.getMonth(), date.getMonth());
    assertEquals(_sqlDate.getDate(), date.getDate());

    // make sure proxied
    assertTrue(!pm.isDirty(pc));
    date.setTime(System.currentTimeMillis() + 1000 * 60 * 60 * 24);
    assertTrue(pm.isDirty(pc));

    endTx(pm);
    assertEquals(date, pc.getSQLDate());
    endEm(pm);
}

From source file:org.libreplan.web.costcategories.CostCategoryCRUDController.java

/**
 * Binds Datebox "init date" to the corresponding attribute of a {@link HourCost}
 *
 * @param dateBoxInitDate//  w  w w .  j av  a2  s.c o m
 * @param hourCost
 */
private void bindDateboxEndDate(final Datebox dateBoxEndDate, final HourCost hourCost) {
    Util.bind(dateBoxEndDate, new Util.Getter<Date>() {

        @Override
        public Date get() {
            LocalDate dateTime = hourCost.getEndDate();
            if (dateTime != null) {
                return new Date(dateTime.getYear() - 1900, dateTime.getMonthOfYear() - 1,
                        dateTime.getDayOfMonth());
            }
            return null;
        }

    }, new Util.Setter<Date>() {

        @Override
        public void set(Date value) {
            if (value != null) {
                hourCost.setEndDate(
                        new LocalDate(value.getYear() + 1900, value.getMonth() + 1, value.getDate()));
            } else {
                hourCost.setEndDate(null);
            }
        }
    });
}

From source file:org.libreplan.web.costcategories.CostCategoryCRUDController.java

/**
 * Binds Datebox "init date" to the corresponding attribute of a {@link HourCost}
 *
 * @param dateBoxInitDate//from w ww .  ja v  a  2 s .  co m
 * @param hourCost
 */
private void bindDateboxInitDate(final Datebox dateBoxInitDate, final HourCost hourCost) {
    Util.bind(dateBoxInitDate, new Util.Getter<Date>() {

        @Override
        public Date get() {
            LocalDate dateTime = hourCost.getInitDate();
            if (dateTime != null) {
                return new Date(dateTime.getYear() - 1900, dateTime.getMonthOfYear() - 1,
                        dateTime.getDayOfMonth());
            } else {
                Date now = new Date();
                hourCost.setInitDate(new LocalDate(now));
                return now;
            }
        }

    }, new Util.Setter<Date>() {

        @Override
        public void set(Date value) {
            if (value != null) {
                hourCost.setInitDate(
                        new LocalDate(value.getYear() + 1900, value.getMonth() + 1, value.getDate()));
            } else {
                hourCost.setInitDate(null);
            }
        }
    });
}

From source file:org.akaza.openclinica.control.admin.UpdateSubjectServlet.java

/**
 * Processes 'confirm' request, validate the subject object
 *
 * @throws Exception//from ww w  .  j  ava2s  .c  o  m
 */
private void confirm(SubjectBean subject, int subjectId) throws Exception {
    FormDiscrepancyNotes discNotes = (FormDiscrepancyNotes) session
            .getAttribute(AddNewSubjectServlet.FORM_DISCREPANCY_NOTES_NAME);
    if (discNotes == null) {
        discNotes = new FormDiscrepancyNotes();
    }
    DiscrepancyValidator v = new DiscrepancyValidator(request, discNotes);
    FormProcessor fp = new FormProcessor(request);

    //        v.addValidation("uniqueIdentifier", Validator.LENGTH_NUMERIC_COMPARISON, NumericComparisonOperator.LESS_THAN_OR_EQUAL_TO, 255);
    //        v.alwaysExecuteLastValidation("uniqueIdentifier");

    if (currentStudy.getStudyParameterConfig().getPersonIdShownOnCRF().equals("true")) {
        v.addValidation("uniqueIdentifier", Validator.LENGTH_NUMERIC_COMPARISON,
                NumericComparisonOperator.LESS_THAN_OR_EQUAL_TO, 255);
        v.alwaysExecuteLastValidation("uniqueIdentifier");
    }

    if (currentStudy.getStudyParameterConfig().getCollectDob().equals("1")) {
        if (!StringUtil.isBlank(fp.getString(DATE_DOB))) {
            v.addValidation(DATE_DOB, Validator.IS_A_DATE);
            v.alwaysExecuteLastValidation(DATE_DOB);
        } else if (StringUtil.isBlank(fp.getString(DATE_DOB)) && subject.getDateOfBirth() != null) {
            Validator.addError(errors, DATE_DOB, resexception.getString("field_not_blank"));
        }
        if (fp.getDate(DATE_DOB) != null) {
            subject.setDateOfBirth(fp.getDate(DATE_DOB));
            String converted_date = local_df.format(subject.getDateOfBirth());
            request.setAttribute(DATE_DOB_TO_SAVE, converted_date);
        }

    }

    else if (currentStudy.getStudyParameterConfig().getCollectDob().equals("2")) {
        if (!StringUtils.isBlank(fp.getString(DATE_DOB))) {

            // if DOB was not updated (and originally entered as a full day, post it as is
            String submitted_date = fp.getString(DATE_DOB);

            boolean isTheSameDate = false;
            try {
                Date fakeDOB = yformat.parse(submitted_date);
                if (subject.getDateOfBirth() != null) {
                    if (subject.getDateOfBirth().getYear() == (fakeDOB.getYear())) {
                        isTheSameDate = true;
                        String converted_date = yformat.format(subject.getDateOfBirth());
                        request.setAttribute(DATE_DOB_TO_SAVE, converted_date);
                    }
                }
            } catch (ParseException pe) {
                logger.debug("update subject: cannot convert date " + submitted_date);
                //I am putting on Pradnya's request the link to code review with a long discussion
                //about what type of logging should be here: enjoy
                //https://dev.openclinica.com/crucible/cru/OC-117
            }

            if (!isTheSameDate) {

                v.addValidation(DATE_DOB, Validator.IS_AN_INTEGER);
                v.alwaysExecuteLastValidation(DATE_DOB);
                v.addValidation(DATE_DOB, Validator.COMPARES_TO_STATIC_VALUE,
                        NumericComparisonOperator.GREATER_THAN_OR_EQUAL_TO, 1000);

                // get today's year
                Date today = new Date();
                Calendar c = Calendar.getInstance();
                c.setTime(today);
                int currentYear = c.get(Calendar.YEAR);
                v.addValidation(DATE_DOB, Validator.COMPARES_TO_STATIC_VALUE,
                        NumericComparisonOperator.LESS_THAN_OR_EQUAL_TO, currentYear);
                int yob = fp.getInt(DATE_DOB);
                Date fakeDate = new Date(yob);
                String dobString = yformat.format(fakeDate);
                try {

                    Date fakeDOB = yformat.parse(dobString);
                    if (yob != 0) {
                        subject.setDateOfBirth(fakeDOB);
                    }
                    request.setAttribute(DATE_DOB_TO_SAVE, yob);
                } catch (ParseException pe) {
                    logger.debug("Parse exception happened.");
                    //I am putting on Pradnya's request the link to code review with a long discussion
                    //about what type of logging should be here: enjoy
                    //https://dev.openclinica.com/crucible/cru/OC-117
                    Validator.addError(errors, DATE_DOB,
                            resexception.getString("please_enter_a_valid_year_birth"));
                }
            }
            request.setAttribute(DATE_DOB, fp.getString(DATE_DOB));

        } else {
            Validator.addError(errors, DATE_DOB, resexception.getString("field_not_blank"));
        }
    }

    errors = v.validate();

    // uniqueIdentifier must be unique in the system
    if (currentStudy.getStudyParameterConfig().getSubjectPersonIdRequired().equals("required")
            || currentStudy.getStudyParameterConfig().getSubjectPersonIdRequired().equals("optional")) {

        String uniqueIdentifier = fp.getString("uniqueIdentifier");
        if (currentStudy.getStudyParameterConfig().getSubjectPersonIdRequired().equals("required")
                && !(subject.getUniqueIdentifier() == null || subject.getUniqueIdentifier().isEmpty())
                && (uniqueIdentifier == null || uniqueIdentifier.isEmpty())) {
            Validator.addError(errors, "uniqueIdentifier", resexception.getString("field_not_blank"));

        }
        if (uniqueIdentifier != null && !uniqueIdentifier.isEmpty()) {

            if (uniqueIdentifier.length() > 255) {
                String descr = resexception.getString("input_provided_is_not")
                        + NumericComparisonOperator.LESS_THAN_OR_EQUAL_TO.getDescription() + " 255 "
                        + resword.getString("characters_long") + ".";
                Validator.addError(errors, "uniqueIdentifier", descr);

            }
            SubjectDAO sdao = new SubjectDAO(sm.getDataSource());
            SubjectBean sub1 = (SubjectBean) sdao.findAnotherByIdentifier(uniqueIdentifier, subject.getId());
            if (sub1.getId() > 0) {
                Validator.addError(errors, "uniqueIdentifier",
                        resexception.getString("person_ID_used_by_another_choose_unique"));
            }
            SubjectBean subjectWithSameId = sdao.findByUniqueIdentifier(uniqueIdentifier);
            if (subjectWithSameId.isActive() && subjectWithSameId.getId() != subject.getId()) {
                Validator.addError(errors, "uniqueIdentifier",
                        resexception.getString("another_assigned_this_ID_choose_unique"));

            }
        }
        subject.setUniqueIdentifier(uniqueIdentifier);
    }

    if (!StringUtil.isBlank(fp.getString("gender"))) {
        subject.setGender(fp.getString("gender").charAt(0));
    } else {
        if (currentStudy.getStudyParameterConfig().getGenderRequired().equals("true")
                && subject.getGender() != ' ') {
            Validator.addError(errors, "gender", resexception.getString("field_not_blank"));
        }
        subject.setGender(' ');
    }

    request.setAttribute("subjectToUpdate", subject);
    if (errors.isEmpty()) {
        forwardPage(Page.UPDATE_SUBJECT_CONFIRM);
    } else {
        //I am putting on Pradnya's request the link to code review with a long discussion
        //about what type of logging should be here: enjoy
        //https://dev.openclinica.com/crucible/cru/OC-117
        logger.error("update subject validation errors");

        setInputMessages(errors);
        setDNFlag(subjectId);
        setLocalDOB(subject);
        if (currentStudy.getStudyParameterConfig().getCollectDob().equals("2"))
            request.setAttribute("localBirthDate", "");

        forwardPage(Page.UPDATE_SUBJECT);
    }
}

From source file:com.edgenius.wiki.blogsync.WordpressProxy.java

/**
 * Return "date_create_gmt" time is gmt, but timezone is wrong - it is local timezone. 
 * Here will correct timezone and return date in local timezone.
 * @param date// w  ww.  j ava  2 s  .  c om
 * @return
 */
private Date fixInputTimezone(Date date) {
    if (date == null)
        return new Date();//???

    Calendar cal = Calendar.getInstance(TimeZone.getTimeZone("GMT"));
    cal.set(Calendar.YEAR, date.getYear() + 1900);
    cal.set(Calendar.MONTH, date.getMonth());
    cal.set(Calendar.DATE, date.getDate());
    cal.set(Calendar.HOUR_OF_DAY, date.getHours());
    cal.set(Calendar.MINUTE, date.getMinutes());
    cal.set(Calendar.SECOND, date.getSeconds());

    Calendar local = Calendar.getInstance(TimeZone.getDefault());
    local.setTimeInMillis(cal.getTimeInMillis());
    return local.getTime();
}

From source file:com.vkassin.mtrade.Common.java

public static void putArcDeal(final Context ctx) {

    final Dialog dialog = new Dialog(ctx);
    dialog.setContentView(R.layout.arcdeal_dialog);
    dialog.setTitle(R.string.ArcDealDialogTitle);

    datetxt = (EditText) dialog.findViewById(R.id.expdateedit);
    SimpleDateFormat sdf = new SimpleDateFormat("dd.MM.yyyy");
    Date dat1 = new Date();
    datetxt.setText(sdf.format(dat1));/*from  ww  w.  ja  v  a 2 s. c  o  m*/
    mYear = dat1.getYear() + 1900;
    mMonth = dat1.getMonth();
    mDay = dat1.getDate();
    final Date dat = new GregorianCalendar(mYear, mMonth, mDay).getTime();

    datetxt.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
            Log.i(TAG, "Show DatePickerDialog");
            DatePickerDialog dpd = new DatePickerDialog(ctx, mDateSetListener, mYear, mMonth, mDay);
            dpd.show();
        }
    });

    TextView itext = (TextView) dialog.findViewById(R.id.instrtext);
    itext.setText(Common.arcfilter);

    Button customDialog_Cancel = (Button) dialog.findViewById(R.id.cancelbutt);
    customDialog_Cancel.setOnClickListener(new Button.OnClickListener() {
        public void onClick(View arg0) {

            dialog.dismiss();
        }

    });

    Button customDialog_Put = (Button) dialog.findViewById(R.id.putorder);
    customDialog_Put.setOnClickListener(new Button.OnClickListener() {
        public void onClick(View arg0) {

            Double price = new Double(0);
            Long qval = new Long(0);
            final EditText pricetxt = (EditText) dialog.findViewById(R.id.priceedit);
            final EditText quanttxt = (EditText) dialog.findViewById(R.id.quantedit);

            try {

                price = Double.valueOf(pricetxt.getText().toString());
            } catch (Exception e) {

                Toast.makeText(ctx, R.string.CorrectPrice, Toast.LENGTH_SHORT).show();
                return;
            }
            try {

                qval = Long.valueOf(quanttxt.getText().toString());
            } catch (Exception e) {

                Toast.makeText(ctx, R.string.CorrectQty, Toast.LENGTH_SHORT).show();
                return;
            }

            //            if (dat.compareTo(new GregorianCalendar(mYear, mMonth, mDay)
            //            .getTime()) > 0) {
            //
            //               Toast.makeText(ctx, R.string.CorrectDate,
            //               Toast.LENGTH_SHORT).show();
            //
            //            return;
            //            }

            long maxkey = 0;
            Iterator<String> itr2 = arcdealMap.keySet().iterator();
            while (itr2.hasNext()) {
                String key1 = itr2.next();
                long k = Long.parseLong(key1);
                if (k > maxkey)
                    maxkey = k;
            }

            Deal adeal = new Deal();
            Iterator<String> itr1 = instrMap.keySet().iterator();
            while (itr1.hasNext()) {
                String key1 = itr1.next();
                Instrument in = instrMap.get(key1);
                if (in.symbol.equals(Common.arcfilter)) {

                    adeal.instrId = Long.valueOf(in.id);
                    break;
                }
            }

            final RadioButton bu0 = (RadioButton) dialog.findViewById(R.id.radio0);

            adeal.price = price;
            adeal.qty = qval;
            adeal.dtime = new GregorianCalendar(mYear, mMonth, mDay).getTimeInMillis();
            adeal.direct = bu0.isChecked() ? Long.valueOf(0) : Long.valueOf(1);
            Collection<String> lacc = Common.getAccountList();
            adeal.account = (lacc == null) ? "" : lacc.iterator().next();
            arcdealMap.put(String.valueOf(maxkey + 1), adeal);
            Common.saveArcDeals();
            Common.arcActivity.refresh();
            dialog.dismiss();
        }
    });

    dialog.show();

    WindowManager.LayoutParams lp = new WindowManager.LayoutParams();
    lp.copyFrom(dialog.getWindow().getAttributes());
    lp.width = WindowManager.LayoutParams.FILL_PARENT;
    lp.height = WindowManager.LayoutParams.FILL_PARENT;
    dialog.getWindow().setAttributes(lp);

}