Example usage for java.text DateFormat parse

List of usage examples for java.text DateFormat parse

Introduction

In this page you can find the example usage for java.text DateFormat parse.

Prototype

public Date parse(String source) throws ParseException 

Source Link

Document

Parses text from the beginning of the given string to produce a date.

Usage

From source file:de.smartics.maven.plugin.buildmetadata.io.SdocBuilder.java

private String formatDate(final String datePropertyKey) {
    final String originalDateString = buildMetaDataProperties.getProperty(datePropertyKey);
    if (StringUtils.isNotBlank(originalDateString)) {
        try {/*www .ja  v  a  2 s  .  com*/
            final String originalPattern = buildMetaDataProperties
                    .getProperty(Constant.PROP_NAME_BUILD_DATE_PATTERN);
            final DateFormat format = new SimpleDateFormat(originalPattern, Locale.ENGLISH);
            final Date date = format.parse(originalDateString);
            final String dateString = DateFormatUtils.ISO_DATETIME_FORMAT.format(date);
            return dateString;
        } catch (final ParseException e) {
            if (LOG.isDebugEnabled()) {
                LOG.debug("Cannot parse date of property '" + datePropertyKey + "': " + originalDateString
                        + ". Skipping...");
            }
            return null;
        }
    }
    return null;
}

From source file:gov.nih.nci.ncicb.tcga.dcc.datareports.service.DatareportsServiceImpl.java

public Predicate genDatePredicate(final Class clazz, final String getter, final boolean before,
        final String dateStr, final DateFormat dateFormat) {
    return new Predicate() {
        public boolean evaluate(Object o) {
            if (dateStr == null || "".equals(dateStr)) {
                return true;
            }/*  w  w w  .  java2 s .c o m*/
            Date date;
            try {
                date = dateFormat.parse(dateStr);
            } catch (ParseException e) {
                return true;
            }
            if (date == null) {
                return true;
            }
            try {
                final Method m = GetterMethod.getGetter(clazz, getter);
                if (before) {
                    return ((Date) m.invoke(clazz.cast(o))).before(date);
                } else {
                    return ((Date) m.invoke(clazz.cast(o))).after(date);
                }
            } catch (Exception e) {
                logger.debug(FancyExceptionLogger.printException(e));
                return true;
            }
        }
    };
}

From source file:heigit.ors.routing.RoutingProfilesUpdater.java

private void run() {
    if (m_isRunning)
        return;/*from w ww . ja  v a2 s.c o  m*/

    m_isRunning = true;

    try {
        long startTime = System.currentTimeMillis();

        LOGGER.info("Start updating profiles...");

        m_nextUpdate = new Date(startTime + m_updatePeriod);

        String osmFile = null;
        String datasource = m_config.DataSource;

        FileUtility.makeDirectory(m_config.WorkingDirectory);

        String md5Sum = null;
        String newMd5Sum = null;
        boolean skipUpdate = false;

        File fileLastUpdate = Paths.get(m_config.WorkingDirectory, "last-update.md5").toFile();
        if (fileLastUpdate.exists())
            md5Sum = FileUtils.readFileToString(fileLastUpdate);

        if (datasource.contains("http")) {
            m_updateStatus = "donwloading data";

            try {
                newMd5Sum = downloadFileContent(datasource + ".md5");
            } catch (Exception ex2) {

            }

            if (md5Sum != null && newMd5Sum != null && md5Sum.contains(newMd5Sum))
                skipUpdate = true;

            if (!skipUpdate) {
                Path path = Paths.get(m_config.WorkingDirectory, FileUtility.getFileName(new URL(datasource)));

                try {
                    downloadFile(datasource, path.toFile());
                } catch (Exception ex) {
                    LOGGER.warning(ex.getMessage());

                    Thread.sleep(300000);

                    m_isRunning = false;
                    run();

                    return;
                }

                osmFile = path.toString();
            }
        } else {
            File file = new File(datasource + ".md5");
            newMd5Sum = file.exists() ? FileUtils.readFileToString(file) : FileUtility.getMd5OfFile(datasource);

            if (md5Sum != null && newMd5Sum != null && md5Sum.contains(newMd5Sum))
                skipUpdate = true;

            if (!skipUpdate) {
                file = new File(datasource);
                Path path = Paths.get(m_config.WorkingDirectory, file.getName());

                // make a local copy of the file
                FileUtils.copyFile(file, path.toFile());

                osmFile = path.toString();
            }
        }

        if (!skipUpdate) {
            if (Helper.isEmpty(newMd5Sum))
                newMd5Sum = FileUtility.getMd5OfFile(osmFile);

            md5Sum = newMd5Sum;
            File file = new File(osmFile);
            String newFileStamp = Long.toString(file.length());

            String tempGraphLocation = Paths.get(m_config.WorkingDirectory, "graph").toString();

            try {
                // Clear directory from a previous build
                File fileGraph = new File(tempGraphLocation);
                if (fileGraph.exists())
                    FileUtils.deleteDirectory(fileGraph);
            } catch (Exception ex) {
            }

            FileUtility.makeDirectory(tempGraphLocation);

            RoutingProfileLoadContext loadCntx = new RoutingProfileLoadContext();
            int nUpdatedProfiles = 0;

            for (RoutingProfile profile : m_routeProfiles.getUniqueProfiles()) {
                RouteProfileConfiguration rpc = profile.getConfiguration();

                Path pathTimestamp = Paths.get(rpc.getGraphPath(), "stamp.txt");
                File file2 = pathTimestamp.toFile();
                if (file2.exists()) {
                    String oldFileStamp = FileUtils.readFileToString(file2);
                    if (newFileStamp.equals(oldFileStamp))
                        continue;
                }

                if (m_updatePeriod > 0) {
                    StorableProperties storageProps = profile.getGraphProperties();
                    DateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");

                    Date importDate = df.parse(storageProps.get("osmreader.import.date"));

                    long diff = startTime - importDate.getTime();

                    if (!DebugUtility.isDebug()) {
                        if (diff < m_updatePeriod)
                            continue;
                    }
                }

                try {
                    m_updateStatus = "preparing profile '" + rpc.getProfiles() + "'";

                    RouteProfileConfiguration rpcNew = rpc.clone();
                    rpcNew.setGraphPath(tempGraphLocation);
                    GraphHopper gh = RoutingProfile.initGraphHopper(osmFile, rpcNew,
                            RoutingProfileManager.getInstance().getProfiles(), loadCntx);

                    if (gh != null) {
                        profile.updateGH(gh);

                        if (RealTrafficDataProvider.getInstance().isInitialized()) {
                            m_updateStatus += ". Performing map matching...";
                            RealTrafficDataProvider.getInstance().updateGraphMatching(profile,
                                    profile.getGraphLocation());
                        }

                        nUpdatedProfiles++;
                    }
                } catch (Exception ex) {
                    LOGGER.severe("Failed to update graph profile. Message:" + ex.getMessage()
                            + "; StackTrace: " + StackTraceUtility.getStackTrace(ex));
                }

                m_updateStatus = null;
            }

            loadCntx.releaseElevationProviderCacheAfterAllVehicleProfilesHaveBeenProcessed();

            FileUtils.writeStringToFile(fileLastUpdate, md5Sum);

            long seconds = (System.currentTimeMillis() - startTime) / 1000;
            LOGGER.info(nUpdatedProfiles + " of " + m_routeProfiles.size() + " profiles were updated in "
                    + seconds + " s.");

            m_updateStatus = "Last update on " + new Date() + " took " + seconds + " s.";
        } else {
            LOGGER.info("No new data is available.");
        }

    } catch (Exception ex) {
        LOGGER.warning(ex.getMessage());
    }

    LOGGER.info("Next route profiles update is scheduled on " + m_nextUpdate.toString());

    m_isRunning = false;
}

From source file:BaseProperties.java

/**
 * Get <code>Date</code> object.
 *///w  w w . jav a2  s  .c  o  m
public Date getDate(final String str, final DateFormat fmt) throws Exception {
    String value = getProperty(str);
    if (value == null) {
        throw new Exception(str + " not found");
    }

    try {
        return fmt.parse(value);
    } catch (ParseException ex) {
        throw new Exception("BaseProperties.getdate()", ex);
    }
}

From source file:com.microsoft.azure.storage.core.Utility.java

/**
 * Returns a GMT date for the specified string in the RFC1123 pattern.
 * // ww w . j ava  2 s  . c  o  m
 * @param value
 *            A <code>String</code> that represents the string to parse.
 * 
 * @return A <code>Date</code> object that represents the GMT date in the RFC1123 pattern.
 * 
 * @throws ParseException
 *             If the specified string is invalid.
 */
public static Date parseRFC1123DateFromStringInGMT(final String value) throws ParseException {
    final DateFormat format = new SimpleDateFormat(RFC1123_PATTERN, Utility.LOCALE_US);
    format.setTimeZone(GMT_ZONE);
    return format.parse(value);
}

From source file:asteroidtracker.AsteroidTrackerSpeechlet.java

/**
 * Function to accept an intent containing a Day slot (date object) and return the Calendar
 * representation of that slot value. If the user provides a date, then use that, otherwise use
 * today. The date is in server time, not in the user's time zone. So "today" for the user may
 * actually be tomorrow./*  w  w  w .  j  a  v a  2s. c  o  m*/
 * 
 * @param intent
 *            the intent object containing the day slot
 * @return the Calendar representation of that date
 */
private Calendar getCalendar(Intent intent) {
    Slot daySlot = intent.getSlot(SLOT_DAY);
    Date date;
    Calendar calendar = Calendar.getInstance();
    if (daySlot != null && daySlot.getValue() != null) {
        DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-d");
        try {
            date = dateFormat.parse(daySlot.getValue());
        } catch (ParseException e) {
            return null;
        }
        calendar.setTime(date);
        return calendar;

    } else {
        return null;
    }

}

From source file:io.heming.accountbook.util.Importer.java

public int importRecords(File file) throws Exception {
    Iterable<CSVRecord> csvRecords;
    List<Record> records = new ArrayList<>();
    try (Reader in = new FileReader(file)) {
        csvRecords = CSVFormat.EXCEL.withQuote('"')
                .withHeader("ID", "CATEGORY", "PRICE", "PHONE", "DATE", "NOTE").parse(in);
        DateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        // ??//  ww w.  ja  va  2  s  .  c  o  m
        categoryFacade.clear();
        int i = 0;
        for (CSVRecord csvRecord : csvRecords) {
            Integer id = Integer.parseInt(csvRecord.get("ID"));
            Category category = new Category(csvRecord.get("CATEGORY"));
            Double price = Double.parseDouble(csvRecord.get("PRICE"));
            String phone = csvRecord.get("PHONE");
            Date date = new Date(format.parse(csvRecord.get("DATE")).getTime());
            String note = csvRecord.get("NOTE");
            // category?
            if (!categoryFacade.list().contains(category)) {
                categoryFacade.add(category);
            }
            Record record = new Record(category, price, phone, date);
            record.setId(id);
            record.setNote(note);
            records.add(record);
        }
    }

    // ??
    recordFacade.clear();
    int i = 0;
    int total = records.size();
    for (Record record : records) {
        recordFacade.add(record);
    }
    return records.size();
}

From source file:com.charts.MaxChart.java

protected OHLCDataItem[] getData(YStockQuote currentStock) throws ParseException {
    ArrayList<OHLCDataItem> dataItems = new ArrayList<OHLCDataItem>();
    DateFormat df;
    if (currentStock instanceof Index)
        df = new SimpleDateFormat("y-MM-dd");
    else//from  w ww  .j a  va 2s  . c o  m
        df = new SimpleDateFormat("dd-MM-yy");
    ArrayList<String> historicalData = currentStock.get_historical_data();
    int startIndex = historicalData.size() - 1;
    while (startIndex > 0) {
        String[] data = historicalData.get(startIndex).split(",");

        Date date = df.parse(data[0]);
        double open = Double.parseDouble(data[1]);
        double high = Double.parseDouble(data[2]);
        double low = Double.parseDouble(data[3]);
        double close = Double.parseDouble(data[4]);
        this.close.addOrUpdate(new Day(date), close);
        double volume;
        try {
            volume = Double.parseDouble(data[5]);
        } catch (NumberFormatException nfe) {
            volume = 0;
        }
        OHLCDataItem item = new OHLCDataItem(date, open, high, low, close, volume);
        dataItems.add(item);
        startIndex -= 3;
    }

    OHLCDataItem[] OHLCData = dataItems.toArray(new OHLCDataItem[dataItems.size()]);
    return OHLCData;
}

From source file:de.meisl.eisstockitems.ImportTest.java

public void importFromFile(String fileName, long categoryId) throws ParseException, IOException {

    List<String> readLines = FileUtils.readLines(new File(fileName), "UTF-8");
    for (String line : readLines) {

        DateFormat format = new SimpleDateFormat("dd.MM.yyyy", Locale.GERMAN);

        String[] split = line.split(",", -1);
        String regNr = split[0];// w  ww . j av  a  2s  .  c  om
        String ifipartnerid = split[1];
        String producerName = split[2];
        Date registrationDate = format.parse(split[3]);
        Date prodCeasedDate = split[4].isEmpty() ? null : format.parse(split[4]);
        Date sellingProhibitedDate = split[5].isEmpty() ? null : format.parse(split[5]);
        Date expiredDate = split[6].isEmpty() ? null : format.parse(split[6]);
        Date sellingCeasedDate = split[7].isEmpty() ? null : format.parse(split[7]);
        String remark = split[8];

        // 1 Eisstockkrper
        // 2 Eisstockkrper fr Schler
        // 3 Stiele
        // 4 Winterlaufsohlen
        // 5 Grundplatten
        // 6 Sommerlaufsohlen mit glatter Laufflche
        // 7 Sommerlaufsohle - rot - Negativprofil (sehr schnel...
        // 8 Sommerlaufsohlen mit Negativprofil
        // 9 Zwischenplatten
        // 10 Runddauben

        Category category = categoryRepository.findOne(categoryId);
        Producer producer;
        Item item;

        List<Producer> findByIfiPartnerId = producerRepository.findByIfiPartnerIdAndName(ifipartnerid,
                producerName);

        int partnerListSize = findByIfiPartnerId.size();
        if (partnerListSize > 0) {
            if (partnerListSize > 1) {
                System.err.println("Many partners for IFI partner ID '" + ifipartnerid + "': "
                        + findByIfiPartnerId.toString());
            }

            producer = findByIfiPartnerId.get(0);

            log.info("Found Producer for ifiPartnerId '" + ifipartnerid + "': " + producer);
        } else {
            log.info("Did not find Producer for ifiPartnerId '" + ifipartnerid + "' and name '" + producerName
                    + "'");
            producer = new Producer();
            producer.setIfiPartnerId(ifipartnerid);
            producer.setName(producerName);
            producer.setUpdated(new Date());
            producer = producerRepository.save(producer);

            log.info("Created Producer for ifiPartnerId '" + ifipartnerid + "': " + producer);
        }

        List<Item> findByRegNumber = itemRepository.findByRegNumber(regNr);
        if (findByRegNumber.size() > 0) {
            if (findByRegNumber.size() > 1) {
                throw new RuntimeException("more than 1 item with regNr '" + regNr + "'");
            }
            item = findByRegNumber.get(0);

            log.info("Found Item for RegNr '" + regNr + "': " + item);
        } else {
            item = new Item();
            item.setCategory(category);
            item.setProducer(producer);
            item.setRegNumber(regNr);
            item.setRemark(remark);
            item.setRegistrationDate(registrationDate);
            item.setExpired(expiredDate);
            item.setProductionCeased(prodCeasedDate);
            item.setSellingCeased(sellingCeasedDate);
            item.setSellingProhibited(sellingProhibitedDate);
            item.setUpdated(new Date());
            item = itemRepository.save(item);

            log.info("Created Item for RegNr '" + regNr + "': " + item);
        }

    }
}

From source file:org.agiso.tempel.Tempel.java

/**
 * /*from ww w .j av a 2 s.  c o  m*/
 * 
 * @param properties
 * @throws Exception 
 */
private Map<String, Object> addRuntimeProperties(Map<String, Object> properties) throws Exception {
    Map<String, Object> props = new HashMap<String, Object>();

    // Okrelanie lokalizacji daty/czasu uywanej do wypenienia paramtrw szablonw
    // zawierajcych dat/czas w formatach DateFormat.SHORT, .MEDIUM, .LONG i .FULL:
    Locale date_locale;
    if (properties.containsKey(UP_DATE_LOCALE)) {
        date_locale = LocaleUtils.toLocale((String) properties.get(UP_DATE_LOCALE));
        Locale.setDefault(date_locale);
    } else {
        date_locale = Locale.getDefault();
    }

    TimeZone time_zone;
    if (properties.containsKey(UP_TIME_ZONE)) {
        time_zone = TimeZone.getTimeZone((String) properties.get(UP_DATE_LOCALE));
        TimeZone.setDefault(time_zone);
    } else {
        time_zone = TimeZone.getDefault();
    }

    // Wyznaczanie daty, na podstawie ktrej zostan wypenione parametry szablonw
    // przechowujce dat/czas w formatach DateFormat.SHORT, .MEDIUM, .LONG i .FULL.
    // Odbywa si w oparciu o wartoci parametrw 'date_format' i 'date'. Parametr
    // 'date_format' definiuje format uywany do parsowania acucha reprezentujcego
    // dat okrelon parametrem 'date'. Parametr 'date_format' moe nie by okrelony.
    // W takiej sytuacji uyty jest format DateFormat.LONG aktywnej lokalizacji (tj.
    // systemowej, ktra moe by przedefiniowana przez parametr 'date_locale'), ktry
    // moe by przedefiniowany przez parametry 'date_format_long' i 'time_format_long':
    Calendar calendar = Calendar.getInstance(date_locale);
    if (properties.containsKey(RP_DATE)) {
        String date_string = (String) properties.get(RP_DATE);
        if (properties.containsKey(RP_DATE_FORMAT)) {
            String date_format = (String) properties.get(RP_DATE_FORMAT);
            DateFormat formatter = new SimpleDateFormat(date_format);
            formatter.setTimeZone(time_zone);
            calendar.setTime(formatter.parse(date_string));
        } else if (properties.containsKey(UP_DATE_FORMAT_LONG) && properties.containsKey(UP_TIME_FORMAT_LONG)) {
            // TODO: Zaoenie, e format data-czas jest zoony z acucha daty i czasu rozdzelonych spacj:
            // 'UP_DATE_FORMAT_LONG UP_TIME_FORMAT_LONG'
            DateFormat formatter = new SimpleDateFormat((String) properties.get(UP_DATE_FORMAT_LONG) + " "
                    + (String) properties.get(UP_TIME_FORMAT_LONG), date_locale);
            formatter.setTimeZone(time_zone);
            calendar.setTime(formatter.parse(date_string));
        } else {
            DateFormat formatter = DateFormat.getDateTimeInstance(DateFormat.LONG, DateFormat.LONG,
                    date_locale);
            formatter.setTimeZone(time_zone);
            calendar.setTime(formatter.parse(date_string));
        }
    }

    // Jeli nie okrelono, wypenianie parametrw przechowujcych poszczeglne
    // skadniki daty, tj. rok, miesic i dzie:
    if (!properties.containsKey(TP_YEAR)) {
        props.put(TP_YEAR, calendar.get(Calendar.YEAR));
    }
    if (!properties.containsKey(TP_MONTH)) {
        props.put(TP_MONTH, calendar.get(Calendar.MONTH));
    }
    if (!properties.containsKey(TP_DAY)) {
        props.put(TP_DAY, calendar.get(Calendar.DAY_OF_MONTH));
    }

    // Jeli nie okrelono, wypenianie parametrw przechowujcych dat i czas w
    // formatach SHORT, MEDIUM, LONG i FULL (na podstawie wyznaczonej lokalizacji):
    Date date = calendar.getTime();
    if (!properties.containsKey(TP_DATE_SHORT)) {
        DateFormat formatter;
        if (properties.containsKey(UP_DATE_FORMAT_SHORT)) {
            formatter = new SimpleDateFormat((String) properties.get(UP_DATE_FORMAT_SHORT), date_locale);
        } else {
            formatter = DateFormat.getDateInstance(DateFormat.SHORT, date_locale);
        }
        formatter.setTimeZone(time_zone);
        props.put(TP_DATE_SHORT, formatter.format(date));
    }
    if (!properties.containsKey(TP_DATE_MEDIUM)) {
        DateFormat formatter;
        if (properties.containsKey(UP_DATE_FORMAT_MEDIUM)) {
            formatter = new SimpleDateFormat((String) properties.get(UP_DATE_FORMAT_MEDIUM), date_locale);
        } else {
            formatter = DateFormat.getDateInstance(DateFormat.MEDIUM, date_locale);
        }
        formatter.setTimeZone(time_zone);
        props.put(TP_DATE_MEDIUM, formatter.format(date));
    }
    if (!properties.containsKey(TP_DATE_LONG)) {
        DateFormat formatter;
        if (properties.containsKey(UP_DATE_FORMAT_LONG)) {
            formatter = new SimpleDateFormat((String) properties.get(UP_DATE_FORMAT_LONG), date_locale);
        } else {
            formatter = DateFormat.getDateInstance(DateFormat.LONG, date_locale);
        }
        formatter.setTimeZone(time_zone);
        props.put(TP_DATE_LONG, formatter.format(date));
    }
    if (!properties.containsKey(TP_DATE_FULL)) {
        DateFormat formatter;
        if (properties.containsKey(UP_DATE_FORMAT_FULL)) {
            formatter = new SimpleDateFormat((String) properties.get(UP_DATE_FORMAT_FULL), date_locale);
        } else {
            formatter = DateFormat.getDateInstance(DateFormat.FULL, date_locale);
        }
        formatter.setTimeZone(time_zone);
        props.put(TP_DATE_FULL, formatter.format(date));
    }

    if (!properties.containsKey(TP_TIME_SHORT)) {
        DateFormat formatter;
        if (properties.containsKey(UP_TIME_FORMAT_SHORT)) {
            formatter = new SimpleDateFormat((String) properties.get(UP_TIME_FORMAT_SHORT), date_locale);
        } else {
            formatter = DateFormat.getTimeInstance(DateFormat.SHORT, date_locale);
        }
        formatter.setTimeZone(time_zone);
        props.put(TP_TIME_SHORT, formatter.format(date));
    }
    if (!properties.containsKey(TP_TIME_MEDIUM)) {
        DateFormat formatter;
        if (properties.containsKey(UP_TIME_FORMAT_MEDIUM)) {
            formatter = new SimpleDateFormat((String) properties.get(UP_TIME_FORMAT_MEDIUM), date_locale);
        } else {
            formatter = DateFormat.getTimeInstance(DateFormat.MEDIUM, date_locale);
        }
        formatter.setTimeZone(time_zone);
        props.put(TP_TIME_MEDIUM, formatter.format(date));
    }
    if (!properties.containsKey(TP_TIME_LONG)) {
        DateFormat formatter;
        if (properties.containsKey(UP_TIME_FORMAT_LONG)) {
            formatter = new SimpleDateFormat((String) properties.get(UP_TIME_FORMAT_LONG), date_locale);
        } else {
            formatter = DateFormat.getTimeInstance(DateFormat.LONG, date_locale);
        }
        formatter.setTimeZone(time_zone);
        props.put(TP_TIME_LONG, formatter.format(date));
    }
    if (!properties.containsKey(TP_TIME_FULL)) {
        DateFormat formatter;
        if (properties.containsKey(UP_TIME_FORMAT_FULL)) {
            formatter = new SimpleDateFormat((String) properties.get(UP_TIME_FORMAT_FULL), date_locale);
        } else {
            formatter = DateFormat.getTimeInstance(DateFormat.FULL, date_locale);
        }
        formatter.setTimeZone(time_zone);
        props.put(TP_TIME_FULL, formatter.format(date));
    }

    return props;
}