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:com.google.api.services.samples.prediction.cmdline.PredictionSample.java

private static Insert2 responseToObject(String jsonString) {

    Insert2 res = new Insert2();
    JSONParser parser = new JSONParser();
    try {//  w ww. j ava2  s  .c  o  m

        JSONObject obj = (JSONObject) parser.parse(jsonString);
        DateFormat formatter = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");
        res.setCreated(new DateTime((Date) formatter.parse((String) obj.get("created"))));
        res.setId((String) obj.get("id"));
        res.setKind((String) obj.get("kind"));
        res.setSelfLink((String) obj.get("selfLink"));
        res.setTrainingStatus((String) obj.get("trainingStatus"));

        if (obj.get("trainingComplete") != null) {

            res.setTrainingComplete(new DateTime((Date) formatter.parse((String) obj.get("trainingComplete"))));
            JSONObject ml = (JSONObject) obj.get("modelInfo");
            Insert2.ModelInfo modelInfo = new ModelInfo();
            modelInfo.setNumberInstances(Long.parseLong((String) ml.get("numberInstances")));
            modelInfo.setModelType((String) ml.get("modelType"));
            modelInfo.setNumberLabels(Long.parseLong((String) ml.get("numberLabels")));
            modelInfo.setClassificationAccuracy((String) ml.get("classificationAccuracy"));
            res.setModelInfo(modelInfo);

        }

    } catch (ParseException e) {
        e.printStackTrace();
        res = null;
    } catch (java.text.ParseException e) {
        e.printStackTrace();
        res = null;
    }
    return res;

}

From source file:com.siphyc.utils.Utilities.java

public static Date combineDateTime(String date, String time) throws ParseException {

    DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm");
    String dateString = date + " " + time;
    return dateFormat.parse(dateString);
}

From source file:com.alu.e3.common.tools.WsseTools.java

public static Date getCreatedDate(String created) throws ParseException {
    Date dateParsed = null;/*from   w  w w  .j  a va2 s . co  m*/
    for (DateFormat format : matchingFormats) {
        try {
            synchronized (format) { // some implementations of SimpleDateFormat are not thread-safe
                dateParsed = format.parse(created);
                return dateParsed;
            }
        } catch (Exception e) {
            // Do nothing, try next format available
        }
    }
    if (dateParsed == null)
        throw new ParseException("Unable to parse date: " + created, 0);
    return dateParsed;
}

From source file:org.linkedeconomy.espa.service.impl.rdf.SubProjectsImpl.java

public static void espaSubprojects() throws ParseException {

    //services for each table
    ApplicationContext ctx = new ClassPathXmlApplicationContext("spring.xml");
    SubProjectsService sub = (SubProjectsService) ctx.getBean("subProjectsServiceImpl");

    List<SubProjects> subProject = sub.getSubProjects();

    //--------------RDF Model--------------//
    Model model = ModelFactory.createDefaultModel();
    Reasoner reasoner = ReasonerRegistry.getOWLReasoner();
    InfModel infModel = ModelFactory.createInfModel(reasoner, model);

    model.setNsPrefix("elod", OntologySpecification.elodPrefix);
    model.setNsPrefix("gr", OntologySpecification.goodRelationsPrefix);
    model.setNsPrefix("dcterms", OntologySpecification.dctermsPrefix);

    //number format
    DecimalFormat df = new DecimalFormat("0.00");

    for (SubProjects subProject1 : subProject) {

        Resource instanceCurrency = infModel.createResource("http://linkedeconomy.org/resource/Currency/EUR");
        Resource instanceBudgetUps = infModel.createResource(OntologySpecification.instancePrefix
                + "UnitPriceSpecification/BudgetItem/" + subProject1.getOps() + "/" + subProject1.getId());
        Resource instanceBudget = infModel.createResource(OntologySpecification.instancePrefix + "BudgetItem/"
                + subProject1.getOps() + "/" + subProject1.getId());
        Resource instanceSubProject = infModel.createResource(OntologySpecification.instancePrefix
                + "Subproject/" + subProject1.getOps() + "/" + subProject1.getId());
        Resource instanceProject = infModel
                .createResource(OntologySpecification.instancePrefix + "Subsidy/" + subProject1.getOps());
        DateFormat dfDate = new SimpleDateFormat("dd/MM/yyyy");
        DateFormat df2 = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
        java.util.Date stDateStarts;
        java.util.Date stDateEnds;
        stDateStarts = dfDate.parse(subProject1.getStart());
        stDateEnds = dfDate.parse(subProject1.getFinish());
        String startDate = df2.format(stDateStarts);
        String endDate = df2.format(stDateEnds);
        infModel.add(instanceProject, RDF.type, OntologySpecification.projectResource);
        infModel.add(instanceBudgetUps, RDF.type, OntologySpecification.priceSpecificationResource);
        infModel.add(instanceBudget, RDF.type, OntologySpecification.budgetResource);
        infModel.add(instanceSubProject, RDF.type, OntologySpecification.subProjectResource);
        instanceProject.addProperty(OntologySpecification.hasRelatedProject, instanceSubProject);
        instanceSubProject.addProperty(OntologySpecification.hasRelatedBudgetItem, instanceBudget);
        instanceBudget.addProperty(OntologySpecification.price, instanceBudgetUps);
        instanceBudgetUps.addProperty(OntologySpecification.hasCurrencyValue,
                df.format(subProject1.getBudget()), XSDDatatype.XSDfloat);
        instanceBudgetUps.addProperty(OntologySpecification.valueAddedTaxIncluded, "true",
                XSDDatatype.XSDboolean);
        instanceBudgetUps.addProperty(OntologySpecification.hasCurrency, instanceCurrency);
        instanceSubProject.addProperty(OntologySpecification.startDate, startDate, XSDDatatype.XSDdateTime);
        instanceSubProject.addProperty(OntologySpecification.endDate, endDate, XSDDatatype.XSDdateTime);
        instanceSubProject.addProperty(OntologySpecification.title, String.valueOf(subProject1.getTitle()),
                "el");
    }// www  .  jav a  2  s .  c o  m

    try {
        FileOutputStream fout = new FileOutputStream(
                "/Users/giovaf/Documents/yds_pilot1/espa_tests/22-02-2016_ouput/subProjectEspa.rdf");
        model.write(fout);
    } catch (IOException e) {
        System.out.println("Exception caught" + e.getMessage());
    }
}

From source file:org.shareok.data.datahandlers.DataHandlersUtil.java

public static String convertFullMonthDateStringFormat(String date) throws ParseException {
    DateFormat fmt = new SimpleDateFormat("dd MMMM yyyy", Locale.US);
    Date d;/*from w w  w  .  j  a va  2  s . c  o m*/
    try {
        d = fmt.parse(date);
    } catch (ParseException ex) {
        fmt = new SimpleDateFormat("MMMM dd, yyyy", Locale.US);
        try {
            d = fmt.parse(date);
        } catch (ParseException ex1) {
            try {
                fmt = new SimpleDateFormat("MMMM dd yyyy", Locale.US);
                d = fmt.parse(date);
            } catch (ParseException ex2) {
                fmt = new SimpleDateFormat("dd MMMM, yyyy", Locale.US);
                d = fmt.parse(date);
            }
        }
    }
    SimpleDateFormat output = new SimpleDateFormat("yyyy-MM-dd");
    return output.format(d);
}

From source file:net.duckling.ddl.web.api.APITeamUpdatesController.java

@SuppressWarnings("deprecation")
private static AoneNoticeParam getMobileTeamNoticeQueryParam(int tid, String date, int offset) {
    AoneNoticeParam p = new AoneNoticeParam(tid, NoticeRule.TEAM_NOTICE, tid + "");
    DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
    Date begin = null;//from  ww w  .j a va 2 s  .  co  m
    try {
        if (date != null) {
            begin = dateFormat.parse(date);
            if (offset > 0) {
                // ??
                Date now = new Date();
                int hour = now.getHours();
                int minute = now.getMinutes();
                long time = begin.getTime() + hour * 60 * 60 * 1000 + minute * 60 * 1000;
                begin = new Date(time);
            }
        } else {
            begin = new Date();
        }
    } catch (ParseException e) {
        begin = new Date();
    }
    p.setBeginDate(DateUtils.addDays(begin, DEFAULT_MOBILE_DURATION));
    p.setEndDate(begin);
    return p;
}

From source file:com.fluidops.iwb.widget.TimelineWidget.java

private static Date parseDate(String dateOriginalFormat) {
    Date date = null;/* w  w w.j  ava2 s. com*/

    // Loop over supported date formats
    for (DateFormat formatter : formatters) {
        try {
            formatter.setTimeZone(TimeZone.getTimeZone("GMT-0"));
            date = (Date) formatter.parse(dateOriginalFormat);
            break;
        }
        // If date format is not supported..
        catch (ParseException e) {
            //ignore, try next formatter
        }
    }
    if (date == null) {
        logger.error("Date format not supported: " + dateOriginalFormat + ". Using today instead.");
        date = new Date();
    }
    return date;
}

From source file:Main.java

/**
 * For some reason, can't find this utility method in the java framework.
 * /*from   www. java2s  .  co m*/
 * @param sDateTime
 *            an xsd:dateTime string
 * @return an equivalent java.util.Date
 * @throws ParseException
 */
public static Date parseXsdDateTime(String sDateTime) throws ParseException {
    final DateFormat format = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'");

    int iDotPosition = NORMAL_IDOT_POSITION;
    if (sDateTime.charAt(0) == '-') {
        iDotPosition = IDOT_POSITION_IFNEG;
    }
    Date result;
    if (sDateTime.length() <= iDotPosition) {
        return format.parse(sDateTime + "Z");
    }

    String millis = null;
    char c = sDateTime.charAt(iDotPosition);
    if (c == '.') {
        // if datetime has milliseconds, separate them
        int eoms = iDotPosition + 1;
        while (Character.isDigit(sDateTime.charAt(eoms))) {
            eoms += 1;
        }
        millis = sDateTime.substring(iDotPosition, eoms);
        sDateTime = sDateTime.substring(0, iDotPosition) + sDateTime.substring(eoms);
        c = sDateTime.charAt(iDotPosition);
    }
    if (c == '+' || c == '-') {
        format.setTimeZone(TimeZone.getTimeZone("GMT" + sDateTime.substring(iDotPosition)));
        sDateTime = sDateTime.substring(0, iDotPosition) + "Z";
    } else if (c != 'Z') {
        throw new ParseException("Illegal timezone specification.", iDotPosition);
    }

    result = format.parse(sDateTime);
    if (millis != null) {
        result.setTime(result.getTime() + Math.round(Float.parseFloat(millis) * ONE_SEC_IN_MILLISECS));
    }

    result = offsetDateFromGMT(result);
    return result;
}

From source file:com.krawler.portal.util.GetterUtil.java

public static Date get(String value, DateFormat df, Date defaultValue) {
    try {// w  w  w .j  a va 2s. c  o m
        Date date = df.parse(value.trim());

        if (date != null) {
            return date;
        }
    } catch (Exception e) {
        logger.warn(e.getMessage(), e);
    }

    return defaultValue;
}

From source file:eu.smartfp7.terrier.sensor.ParserUtility.java

public static EdgeNodeSnapShot parseShort(InputStream is) throws Exception {

    DocumentBuilderFactory xmlfact = DocumentBuilderFactory.newInstance();
    xmlfact.setNamespaceAware(true);//from  w w  w  .  j  a  v a 2  s.c  o  m
    Document document = xmlfact.newDocumentBuilder().parse(is);

    XPath xpath = XPathFactory.newInstance().newXPath();

    String time = (String) xpath.compile("//crowd/time/text()").evaluate(document, XPathConstants.STRING);

    DateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");
    Calendar c = Calendar.getInstance();
    ;
    c.setTime(df.parse(time));

    String density = (String) xpath.compile("//crowd/density/text()").evaluate(document, XPathConstants.STRING);

    NodeList list = (NodeList) xpath.compile("//crowd/colour").evaluate(document, XPathConstants.NODESET);
    double[] colors = new double[list.getLength()];
    for (int i = 0; i < list.getLength(); i++) {
        org.w3c.dom.Node colorNode = list.item(i);
        String v = colorNode.getFirstChild().getTextContent();
        colors[i] = new Double(v);
    }

    String activity = (String) xpath.compile("//activity/name/text()").evaluate(document,
            XPathConstants.STRING);

    CrowdReport crowdReport = new CrowdReport(null, new Double(density), 0.0, colors);

    EdgeNodeSnapShot snapShot = new EdgeNodeSnapShot(null, null, c, crowdReport);
    snapShot.setText((activity != null ? activity : StringUtils.EMPTY));

    return snapShot;

}