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:applica.framework.modules.LicenseModule.java

@Action(value = "generate", description = "Generate a new license file")
public void generate(Properties properties) {
    File file = new File(LicenseManager.LICENSE_FILE);
    if (file.exists()) {
        p("Cannot create license file: %s already exists", LicenseManager.LICENSE_FILE);
        return;/*from  ww  w .  j  av a  2 s. c o m*/
    }

    String user = properties.getProperty("user");

    if (StringUtils.isEmpty(user)) {
        p("Please specify a user (-Duser={user}");
        return;
    }

    String dateString = properties.getProperty("validity");

    if (StringUtils.isEmpty(dateString)) {
        p("Please specify a user (-validity={yyyy-MM-dd}");
        return;
    }

    DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
    Date date = null;
    try {
        date = dateFormat.parse(dateString);
    } catch (ParseException e) {
        p("Bad date format. Use yyyy-MM-dd");
        return;
    }

    if (date != null) {
        try {
            LicenseManager.instance().generateLicenseFile(user, date, file.getAbsolutePath());

            p("License generated: %s", file.getAbsolutePath());
        } catch (LicenseGenerationException e) {
            p("Error generating license file: %s", e.getMessage());
        }
    }
}

From source file:org.jivesoftware.openfire.reporting.graph.GraphEngine.java

public static long[] parseTimePeriod(String timeperiod) {

    if (null == timeperiod)
        timeperiod = "last60minutes";

    Date fromDate = null;//w  w  w  . ja  v a2 s . c o m
    Date toDate = null;
    long dataPoints = 60;

    Calendar cal = Calendar.getInstance();
    Date now = cal.getTime();
    // Reset the day fields so we're at the beginning of the day.
    cal.set(Calendar.HOUR, 0);
    cal.set(Calendar.MINUTE, 0);
    cal.set(Calendar.SECOND, 0);
    cal.set(Calendar.MILLISECOND, 0);
    // Compute "this week" by resetting the day of the week to the first day of the week
    cal.set(Calendar.DAY_OF_WEEK, cal.getFirstDayOfWeek());
    Date thisWeekStart = cal.getTime();
    Date thisWeekEnd = now;
    // Compute last week - start with the end boundary which is 1 millisecond before the start of this week
    cal.add(Calendar.MILLISECOND, -1);
    Date lastWeekEnd = cal.getTime();
    // Add that millisecond back, subtract 7 days for the start boundary of "last week"
    cal.add(Calendar.MILLISECOND, 1);
    cal.add(Calendar.DAY_OF_YEAR, -7);
    Date lastWeekStart = cal.getTime();
    // Reset the time
    cal.setTime(now);
    cal.set(Calendar.HOUR, 0);
    cal.set(Calendar.MINUTE, 0);
    cal.set(Calendar.SECOND, 0);
    cal.set(Calendar.MILLISECOND, 0);
    // Reset to the 1st day of the month, make the the start boundary for "this month"
    cal.set(Calendar.DAY_OF_MONTH, cal.getMinimum(Calendar.DAY_OF_MONTH));
    Date thisMonthStart = cal.getTime();
    Date thisMonthEnd = now;
    // Compute last month
    cal.add(Calendar.MILLISECOND, -1);
    Date lastMonthEnd = cal.getTime();
    cal.add(Calendar.MILLISECOND, 1);
    cal.add(Calendar.MONTH, -1);
    Date lastMonthStart = cal.getTime();
    // Compute last 3 months
    cal.setTime(now);
    cal.add(Calendar.MONTH, -2);
    cal.set(Calendar.HOUR, 0);
    cal.set(Calendar.MINUTE, 0);
    cal.set(Calendar.SECOND, 0);
    cal.set(Calendar.MILLISECOND, 0);
    Date last3MonthsStart = cal.getTime();
    Date last3MonthsEnd = now;
    // Compute last 7 days:
    cal.setTime(now);
    cal.add(Calendar.DAY_OF_YEAR, -6);
    cal.set(Calendar.HOUR, 0);
    cal.set(Calendar.MINUTE, 0);
    cal.set(Calendar.SECOND, 0);
    cal.set(Calendar.MILLISECOND, 0);
    Date last7DaysStart = cal.getTime();
    Date last7DaysEnd = now;
    // Compute last 60 minutes;
    cal.setTime(now);
    cal.add(Calendar.MINUTE, -60);
    Date last60MinutesStart = cal.getTime();
    Date last60MinutesEnd = now;
    // Compute last 24 hours;
    cal.setTime(now);
    cal.add(Calendar.HOUR, -23);
    Date last24HoursStart = cal.getTime();
    Date last24HoursEnd = now;
    // Done, reset the cal internal date to now
    cal.setTime(now);

    if ("thisweek".equals(timeperiod)) {
        fromDate = thisWeekStart;
        toDate = thisWeekEnd;
        dataPoints = 7;
    } else if ("last7days".equals(timeperiod)) {
        fromDate = last7DaysStart;
        toDate = last7DaysEnd;
        dataPoints = 7;
    } else if ("lastweek".equals(timeperiod)) {
        fromDate = lastWeekStart;
        toDate = lastWeekEnd;
        dataPoints = 7;
    } else if ("thismonth".equals(timeperiod)) {
        fromDate = thisMonthStart;
        toDate = thisMonthEnd;
        dataPoints = 30;
    } else if ("lastmonth".equals(timeperiod)) {
        fromDate = lastMonthStart;
        toDate = lastMonthEnd;
        dataPoints = 30;
    } else if ("last3months".equals(timeperiod)) {
        fromDate = last3MonthsStart;
        toDate = last3MonthsEnd;
        dataPoints = (long) Math.ceil((toDate.getTime() - fromDate.getTime()) / WEEK);
    } else if ("last60minutes".equals(timeperiod)) {
        fromDate = last60MinutesStart;
        toDate = last60MinutesEnd;
        dataPoints = 60;
    } else if ("last24hours".equals(timeperiod)) {
        fromDate = last24HoursStart;
        toDate = last24HoursEnd;
        dataPoints = 48;
    } else {
        String[] dates = timeperiod.split("to");
        if (dates.length > 0) {
            DateFormat formDateFormatter = new SimpleDateFormat("MM/dd/yy");
            String fromDateParam = dates[0];
            String toDateParam = dates[1];
            if (fromDateParam != null) {
                try {
                    fromDate = formDateFormatter.parse(fromDateParam);
                } catch (Exception e) {
                    // ignore formatting exception
                }
            }
            if (toDateParam != null) {
                try {
                    toDate = formDateFormatter.parse(toDateParam);
                    // Make this date be the end of the day (so it's the day *inclusive*, not *exclusive*)
                    Calendar adjusted = Calendar.getInstance();
                    adjusted.setTime(toDate);
                    adjusted.set(Calendar.HOUR_OF_DAY, 23);
                    adjusted.set(Calendar.MINUTE, 59);
                    adjusted.set(Calendar.SECOND, 59);
                    adjusted.set(Calendar.MILLISECOND, 999);
                    toDate = adjusted.getTime();
                } catch (Exception e) {
                    // ignore formatting exception
                }
            }
            dataPoints = discoverDataPoints(fromDate, toDate);
        }
    }

    // default to last 60 minutes
    if (null == fromDate && null == toDate) {
        return new long[] { last60MinutesStart.getTime(), last60MinutesEnd.getTime(), dataPoints };
    } else if (null == fromDate) {
        return new long[] { 0, toDate.getTime(), dataPoints };
    } else if (null == toDate) {
        return new long[] { fromDate.getTime(), now.getTime(), dataPoints };
    } else {
        return new long[] { fromDate.getTime(), toDate.getTime(), dataPoints };
    }
}

From source file:org.openmrs.module.patientportaltoolkit.fragment.controller.ProfileEditFragmentController.java

public void saveProfileEditForm(FragmentModel model,
        @RequestParam(value = "personId", required = true) int personId,
        @RequestParam(value = "givenName", required = true) String givenName,
        @RequestParam(value = "familyName", required = true) String familyName,
        @RequestParam(value = "gender", required = true) String gender,
        @RequestParam(value = "birthDate", required = true) String birthDate, PageRequest pageRequest) {

    log.info(PPTLogAppender.appendLog("SAVE_PROFILEEDIT", pageRequest.getRequest(), "personId:", personId + "",
            "givenName:", givenName, "familyName", familyName, "gender", gender, "birthDate", birthDate));
    Person person = Context.getPersonService().getPerson(personId);
    PersonName personName = new PersonName();
    personName.setGivenName(givenName);/* w  w w .  ja  v  a 2 s. c  o  m*/
    personName.setFamilyName(familyName);
    Set<PersonName> personNames = person.getNames();

    boolean personNameExists = false;
    for (PersonName pn : personNames) {
        if (pn.equalsContent(personName))
            personNameExists = true;
    }
    if (!personNameExists) {
        for (PersonName pn : personNames) {
            if (pn.getPreferred())
                pn.setPreferred(false);
        }
        personName.setPreferred(true);
        personNames.add(personName);
    }

    person.setNames(personNames);

    DateFormat df = new SimpleDateFormat("mm/dd/yyyy");
    try {
        person.setBirthdate(df.parse(birthDate));
    } catch (ParseException e) {
        e.printStackTrace();
    }

    if (gender != null)
        person.setGender(gender);
    Context.getPersonService().savePerson(person);
    //log.info("Profile Details saved for -" + Context.getAuthenticatedUser().getPersonName() + "(id=" + Context.getAuthenticatedUser().getPerson().getPersonId() + ",uuid=" + Context.getAuthenticatedUser().getPerson().getUuid() + ")" + " Requested by - " + Context.getAuthenticatedUser().getPersonName() + "(id=" + Context.getAuthenticatedUser().getPerson().getPersonId() + ",uuid=" + Context.getAuthenticatedUser().getPerson().getUuid() + ")");
}

From source file:com.haulmont.chile.core.datatypes.impl.TimeDatatype.java

@Override
public Date parse(String value, Locale locale) throws ParseException {
    if (StringUtils.isBlank(value)) {
        return null;
    }//from   ww w .  j  a v a2  s.c  o  m

    FormatStrings formatStrings = AppBeans.get(FormatStringsRegistry.class).getFormatStrings(locale);
    if (formatStrings == null) {
        return parse(value);
    }

    DateFormat format = new SimpleDateFormat(formatStrings.getTimeFormat());
    return format.parse(value.trim());
}

From source file:grails.plugins.crm.core.CustomDateEditor.java

@Override
public void setAsText(final String text) throws IllegalArgumentException {
    if (!StringUtils.hasText(text)) {
        setValue(null); // Treat empty String as null value.
    } else {//from w  ww . ja va  2s .c o  m
        Exception error = null;
        java.util.Date date = null;
        for (int i = 0; i < DATE_FORMATS.length; i++) {
            try {
                DateFormat df = new SimpleDateFormat(DATE_FORMATS[i]);
                df.setLenient(false);
                date = df.parse(text);
            } catch (ParseException ex) {
                if (error == null) {
                    error = ex;
                }
            }
            if (date != null) {
                setValue(sql ? new java.sql.Date(date.getTime()) : date);
                error = null;
                break; // We've found a valid date.
            }
        }
        if (error != null) {
            throw new IllegalArgumentException("Could not parse date: " + error.getMessage());
        }
    }
}

From source file:com.janoz.tvapilib.thetvdb.impl.EpisodeParser.java

private Date parseDate(String src) {
    DateFormat df = new SimpleDateFormat("yyyy-MM-dd");
    try {// w w  w  .  j a  v a  2s .c  o m
        return new Date(df.parse(src).getTime());
    } catch (ParseException e) {
        throw new TvApiException("Unable to retreive date from '" + src + "'.", e);
    }
}

From source file:be.wegenenverkeer.common.resteasy.json.Iso8601AndOthersDateFormat.java

@Override
public Date parse(String str, ParsePosition pos) {
    Date date = null;//www . j a  v  a  2 s  .  c  o m

    if (!StringUtils.isBlank(str)) {
        // try ISO 8601 format first
        try {
            return iso8601NozoneFormat.parse(str, pos);
        } catch (IllegalArgumentException iae) {
            // ignore, try next format
            date = null; // dummy
        }

        // then try a list of formats
        for (String format : FORMATS) {
            DateFormat formatter = new SimpleDateFormat(format, Locale.US);
            try {
                return formatter.parse(str);
            } catch (ParseException e) {
                // ignore, try next format
                date = null; // dummy
            }
        }
        throw new IllegalArgumentException("Could not parse date " + str
                + " using ISO 8601 or any of the formats " + Arrays.asList(FORMATS) + ".");

    }
    return date; // empty string

}

From source file:org.jasig.cas.web.LicenceFilter.java

public void init(FilterConfig config) throws ServletException {
    //licence//  w  w w  .java  2  s .co  m
    String liurl = config.getInitParameter("liurl");
    if (liurl == null || liurl.isEmpty()) {
        throw new ServletException();
    }
    CloseableHttpClient httpclient = HttpClients.createDefault();
    HttpGet httpGet = new HttpGet(liurl);
    httpGet.addHeader("accept", "application/json");
    CloseableHttpResponse response1 = null;
    try {
        response1 = httpclient.execute(httpGet);
        if (response1.getStatusLine().getStatusCode() != 200) {
            System.out.println("licence ");
            throw new ServletException();
        }
        HttpEntity entity1 = response1.getEntity();
        BufferedReader br = new BufferedReader(new InputStreamReader((entity1.getContent())));
        String output;
        StringBuilder sb = new StringBuilder();
        while ((output = br.readLine()) != null) {
            sb.append(output);
        }
        JSONObject jsonObject = new JSONObject(sb.toString());
        String error = jsonObject.getString("code");
        if (!error.equals("S_OK")) {
            System.out.println("licence ");
            throw new ServletException();
        }
        String strexprietime = jsonObject.getJSONObject("var").getJSONObject("licInfo").getString("expireTime");
        DateFormat df = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
        this.expiretime = df.parse(strexprietime).getTime();
        EntityUtils.consume(entity1);
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        try {
            response1.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

}

From source file:com.spend.spendService.SearchText.java

private void Search() {
    try {/*w  w  w.ja v  a2  s  . com*/
        TimerTask timertask = new TimerTask() {
            public void run() {
                try {
                    String[] seList = getSearchEngineNamesArray();
                    /* get search queries from keywords table */
                    PreparedStatement psmt = con.prepareStatement("SELECT searchKeyword FROM keywords");
                    ResultSet rs = psmt.executeQuery();
                    while (rs.next()) {
                        searchQuery = rs.getString("searchKeyword");
                        /* insert search queries into searchqueue table */
                        for (Object se : seList) {
                            PreparedStatement psmt1 = con.prepareStatement(
                                    "INSERT INTO searchqueue(searchText,disabled,searchEngineName) VALUES(?,0,?);");
                            psmt1.setString(1, searchQuery);
                            psmt1.setString(2, se.toString());
                            psmt1.executeUpdate();
                            psmt1.close();
                        }
                    }
                } catch (Exception ex) {
                    System.out.println("SearchText.java timertask run function SQL ERROR " + ex.getMessage());
                }
            }
        };
        Timer timer = new Timer();
        DateFormat dateformat = new SimpleDateFormat("dd-MM-yyyy HH:mm:ss");
        Date date = dateformat.parse("20-07-2017 00:00:00"); // set time and date
        timer.schedule(timertask, date, 1000 * 60 * 60 * 24); // for 24 hour 1000*60*60*24
    } catch (Exception ex) {
        System.out.println("SearchText.java Search function ERROR " + ex.getMessage());
    }
}

From source file:com.upscale.front.service.util.TextExtractionUtil.java

public Date extractDOB(String text, String type) {

    if (type.equals("PANCARD")) {
        Pattern pattern = Pattern.compile("(0[1-9]|[12][0-9]|3[01])[- /.](0[1-9]|1[012])[- /.](19|20)\\d\\d");
        String result = null;/*  ww  w.  j  a va2 s.c o  m*/
        String[] data = org.apache.commons.lang.StringUtils.split(text, "\n");
        for (String str : data) {
            Matcher matcher = pattern.matcher(str);
            if (matcher.matches())
                result = str;
        }

        DateFormat df = new SimpleDateFormat("dd/MM/yyyy");
        Date dob = new Date();
        try {
            dob = df.parse(result);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return dob;
    } else
        return null;

}