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.edgenius.wiki.ext.calendar.web.CalendarAction.java

public String quickAdd() {
    QuickReturnJson json = new QuickReturnJson();
    if (StringUtils.isBlank(calendarName)) {
        json.setIsSuccess(false);/*from  ww  w. ja  va2 s  .  co m*/
        json.setMsg("Unable to get valid calendar name");
    } else {
        try {
            Calendar cal = calendarService.getCalendar(pageUuid, calendarName);
            if (cal == null) {
                cal = new Calendar();
                cal.setName(calendarName);
                cal.setPageUuid(pageUuid);
                WikiUtil.setTouchedInfo(userReadingService, cal);
                calendarService.saveOrUpdateCalendar(cal);
            }
            CalendarEvent evt = new CalendarEvent();
            evt.setCalendar(cal);
            evt.setAllDayEvent(isAllDayEvent > 0);

            DateFormat format = getDateFormat();
            Date start = format.parse(calendarStartTime);
            Date end = format.parse(calendarEndTime);
            evt.setStart(start);
            evt.setEnd(end);
            WikiUtil.setTouchedInfo(userReadingService, evt);
            evt.setSubject(calendarTitle);
            calendarService.saveOrUpdateEvent(evt);

            json.setIsSuccess(true);
            json.setMsg("Save success");
            json.setData(String.valueOf(evt.getUid()));
        } catch (ParseException e) {
            json.setIsSuccess(false);
            json.setMsg("Unable to get valid calendar start/end date");
            log.error("Unable to parse calendar start/end date format", e);
        } catch (Exception e) {
            json.setIsSuccess(false);
            json.setMsg("Save calendar event failed.");
            log.error("Save calendar error", e);
        }
    }
    try {
        Gson gson = new Gson();
        String jsonstr = gson.toJson(json);
        getResponse().getOutputStream().write(jsonstr.getBytes(Constants.UTF8));
    } catch (IOException e) {
        log.error("unable response event save request", e);
    }
    return null;
}

From source file:com.mycompany.controllers.PlayerController.java

@RequestMapping(value = "/edit/{idPlayer}", method = RequestMethod.POST)
public ModelAndView editteam(@Valid PlayerForm playerForm, @PathVariable("idClub") String idClub,
        @PathVariable("idSection") String idSection, @PathVariable("idTeam") String idTeam, Model model,
        @PathVariable("idPlayer") String idPlayer) throws ParseException {
    Configuration cfg = new Configuration();
    cfg.configure("hibernate.cfg.xml");
    SessionFactory factory = cfg.buildSessionFactory();
    Session session = factory.openSession();
    Transaction t = session.beginTransaction();

    Zawodnik player = session.find(Zawodnik.class, Integer.parseInt(idPlayer));
    player.setImie(playerForm.getName());
    player.setNazwisko(playerForm.getLastname());
    String year = playerForm.getYear();
    String day = playerForm.getDay();
    String month = playerForm.getMonth();
    player.setWaga(Integer.parseInt(playerForm.getWeight()));
    player.setWzrost(Integer.parseInt(playerForm.getHeight()));
    DateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
    StringBuilder s = new StringBuilder(year);
    s.append("-");
    s.append(month);//from  w  ww  .  jav a 2  s. c o  m
    s.append("-");
    s.append(day);
    Date myDate = formatter.parse(s.toString());
    java.sql.Date sqlDate = new java.sql.Date(myDate.getTime());
    player.setDataUrodzenia(sqlDate);
    t.commit();
    session.close();
    return new ModelAndView(
            "redirect:/club/" + idClub + "/sections/" + idSection + "/teams/" + idTeam + "/players/");

}

From source file:org.hyperic.hq.hqapi1.tools.MaintenanceCommand.java

/**
 * Function that takes a user given date string and attempts to convert it to
 * a Java Date object.  One of 2 formats are supported:
 *
 * 1) Date/Time format as defined by SimpleDateFormat (i.e. 5/18/2008 4:00 PM)
 * 2) Hour/Minutes notation.  In this case, the current date is used.
 *
 * @param str The date string to parse.// ww  w.  j av a  2s  .co m
 * @return The equivenlent Date object, or null if the date could not be parsed.
 */
private Date parseDateString(String str) {
    final DateFormat df = SimpleDateFormat.getInstance();
    try {
        return df.parse(str);
    } catch (ParseException e) {
        // Ignored
    }

    // Fall back to HH:MM notation if date parse fails.
    String time[] = str.split(":");
    if (time.length != 2) {
        return null;
    }

    try {
        int hours = Integer.parseInt(time[0]);
        int minutes = Integer.parseInt(time[1]);
        Calendar c = Calendar.getInstance();
        c.set(Calendar.HOUR_OF_DAY, hours);
        c.set(Calendar.MINUTE, minutes);
        return c.getTime();
    } catch (NumberFormatException e) {
        return null;
    }
}

From source file:com.mycompany.controllers.PlayerController.java

@RequestMapping(value = "/create", method = RequestMethod.POST)
public ModelAndView createplayer(@Valid PlayerForm playerForm, @PathVariable("idClub") String idClub,
        @PathVariable("idSection") String idSection, @PathVariable("idTeam") String idTeam, Model model)
        throws ParseException {
    Configuration cfg = new Configuration();
    cfg.configure("hibernate.cfg.xml");
    SessionFactory factory = cfg.buildSessionFactory();
    Session session = factory.openSession();
    Transaction t = session.beginTransaction();
    Druzyna team = session.find(Druzyna.class, Integer.parseInt(idTeam));

    Zawodnik player = new Zawodnik();
    player.setImie(playerForm.getName());

    String year = playerForm.getYear();
    String day = playerForm.getDay();
    String month = playerForm.getMonth();

    DateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
    StringBuilder s = new StringBuilder(year);
    s.append("-");
    s.append(month);/*from   w w  w .j  a v  a 2s .  co  m*/
    s.append("-");
    s.append(day);
    Date myDate = formatter.parse(s.toString());
    java.sql.Date sqlDate = new java.sql.Date(myDate.getTime());
    player.setDataUrodzenia(sqlDate);
    player.setNazwisko(playerForm.getLastname());
    player.setWaga(Integer.parseInt(playerForm.getWeight()));
    player.setWzrost(Integer.parseInt(playerForm.getHeight()));
    player.setIdDruzyna(team);
    session.persist(player);
    t.commit();
    session.close();
    factory.close();
    return new ModelAndView(
            "redirect:/club/" + idClub + "/sections/" + idSection + "/teams/" + idTeam + "/players/");
}

From source file:com.skilrock.lms.coreEngine.accMgmt.common.ProcessPendingPWTHelper.java

private java.sql.Date getDate(String date) {

    logger.debug("Passed date::" + date);
    String format = "yyyy-MM-dd";
    DateFormat dateFormat = new SimpleDateFormat(format);
    try {//  w  ww  .j  a  va2 s.com

        Date parsedDate = dateFormat.parse(date);
        logger.debug("Parsed date::" + parsedDate);
        logger.debug(new java.sql.Date(parsedDate.getTime()));
        return new java.sql.Date(parsedDate.getTime());

    } catch (ParseException e) {
        logger.error("Exception: " + e);
        e.printStackTrace();
    }
    return null;
}

From source file:com.wipro.ats.bdre.md.rest.ext.DataGenAPI.java

@RequestMapping(value = { "/createjobs" }, method = RequestMethod.POST)

@ResponseBody/* w  ww .  ja v a  2  s. co  m*/
public RestWrapper createJobs(@RequestParam Map<String, String> map, Principal principal) {
    LOGGER.debug(" value of map is " + map.size());
    RestWrapper restWrapper = null;
    Process parentProcess = null;
    Process childProcess = null;
    Properties jpaProperties = null;

    String processName = null;
    String processDescription = null;
    Integer busDomainId = null;

    StringBuilder tableSchema = new StringBuilder("");
    //to handle argument id's in sequence if rows are deleted and added in UI
    int fieldArgCounter = 1;
    int fieldTypeCounter = 0;
    int fieldCounter = 1;
    String[] dateContent;
    StringBuilder unifiedDate = new StringBuilder("");
    Date date = null, date2 = null;

    List<Properties> childProps = new ArrayList<>();
    Map<String, String> orderedMap = new TreeMap<>(map);
    //inserting in properties table
    for (String string : orderedMap.keySet()) {
        LOGGER.debug("String is" + string);
        if (map.get(string) == null || ("").equals(map.get(string))) {
            continue;
        }
        Integer splitIndex = string.lastIndexOf("_");
        String key = string.substring(splitIndex + 1, string.length());
        LOGGER.debug("key is " + key);

        if (string.startsWith("type_genArg") && map.get(string).split(",").length == 3) {
            fieldTypeCounter = Integer.parseInt(string.substring(string.lastIndexOf(".") + 1, string.length()));
            LOGGER.debug("genArg key Index" + fieldTypeCounter);

            dateContent = map.get(string).split(",");
            DateFormat dF = new SimpleDateFormat(dateContent[2]);
            try {
                date = dF.parse(dateContent[0]);
                date2 = dF.parse(dateContent[1]);
            } catch (ParseException e) {
                LOGGER.debug("error in Date entry");
            }
            unifiedDate.append(date.getTime() + "," + date2.getTime() + "," + dateContent[2]);
            jpaProperties = Dao2TableUtil.buildJPAProperties("data", "args." + fieldArgCounter,
                    unifiedDate.toString(), "Generated Argument");
            childProps.add(jpaProperties);
            jpaProperties = Dao2TableUtil.buildJPAProperties("data", "data-gen-id." + fieldArgCounter,
                    map.get("type_generatedType." + fieldTypeCounter), "Generated Type");
            childProps.add(jpaProperties);
            fieldArgCounter++;
        } else if (string.startsWith("type_genArg")) {
            fieldTypeCounter = Integer.parseInt(string.substring(string.lastIndexOf(".") + 1, string.length()));
            LOGGER.debug("genArg key Index" + fieldTypeCounter);
            jpaProperties = Dao2TableUtil.buildJPAProperties("data", "args." + fieldArgCounter, map.get(string),
                    "Generated Argument");
            childProps.add(jpaProperties);
            jpaProperties = Dao2TableUtil.buildJPAProperties("data", "data-gen-id." + fieldArgCounter,
                    map.get("type_generatedType." + fieldTypeCounter), "Generated Type");
            childProps.add(jpaProperties);
            fieldArgCounter++;
        }

        else if (string.startsWith("type_fieldName")) {
            LOGGER.debug("type_fieldName" + tableSchema);
            tableSchema.append(map.get(string) + ":" + fieldCounter++ + ",");
        } else if (string.startsWith("other_numRows")) {
            LOGGER.debug("other_numRows" + map.get(string));
            jpaProperties = Dao2TableUtil.buildJPAProperties("data", key, map.get(string), "number of rows");
            childProps.add(jpaProperties);
        } else if (string.startsWith("other_numSplits")) {
            LOGGER.debug("other_numSplits" + map.get(string));
            jpaProperties = Dao2TableUtil.buildJPAProperties("data", key, map.get(string), "number of splits");
            childProps.add(jpaProperties);
        } else if (string.startsWith("other_tableName")) {
            LOGGER.debug("other_tableName" + map.get(string));
            jpaProperties = Dao2TableUtil.buildJPAProperties(TABLE, key, map.get(string), "Table Name");
            childProps.add(jpaProperties);
        } else if (string.startsWith("other_separator")) {
            LOGGER.debug("other_separator" + map.get(string));
            jpaProperties = Dao2TableUtil.buildJPAProperties(TABLE, key, map.get(string), "Separator");
            childProps.add(jpaProperties);
        } else if (string.startsWith("process_processName")) {
            LOGGER.debug("process_processName" + map.get(string));
            processName = map.get(string);
        } else if (string.startsWith("process_outputPath")) {
            LOGGER.debug("process_outputPath" + map.get(string));
            jpaProperties = Dao2TableUtil.buildJPAProperties(TABLE, key, map.get(string), "Output path");
            childProps.add(jpaProperties);
        } else if (string.startsWith("process_processDescription")) {
            LOGGER.debug("process_processDescription" + map.get(string));
            processDescription = map.get(string);
        } else if (string.startsWith("process_busDomainId")) {
            LOGGER.debug("process_busDomainId" + map.get(string));
            busDomainId = new Integer(map.get(string));
        }

    }
    parentProcess = Dao2TableUtil.buildJPAProcess(18, processName, processDescription, 1, busDomainId);
    Users users = new Users();
    users.setUsername(principal.getName());
    parentProcess.setUsers(users);
    parentProcess.setUserRoles(userRolesDAO.minUserRoleId(principal.getName()));
    childProcess = Dao2TableUtil.buildJPAProcess(14, "SubProcess of " + processName, processDescription, 0,
            busDomainId);

    //remove last : in tableSchema String
    tableSchema.deleteCharAt(tableSchema.length() - 1);
    jpaProperties = Dao2TableUtil.buildJPAProperties(TABLE, "tableSchema", tableSchema.toString(),
            "Table Schema");
    childProps.add(jpaProperties);
    //creating parent and child processes and inserting properties
    List<Process> processList = processDAO.createOneChildJob(parentProcess, childProcess, null, childProps);
    List<com.wipro.ats.bdre.md.beans.table.Process> tableProcessList = Dao2TableUtil
            .jpaList2TableProcessList(processList);
    Integer counter = tableProcessList.size();
    for (com.wipro.ats.bdre.md.beans.table.Process process : tableProcessList) {
        process.setCounter(counter);
        process.setTableAddTS(DateConverter.dateToString(process.getAddTS()));
        process.setTableEditTS(DateConverter.dateToString(process.getEditTS()));
    }
    restWrapper = new RestWrapper(tableProcessList, RestWrapper.OK);
    LOGGER.info("Process and Properties for data generation process inserted by" + principal.getName());
    return restWrapper;
}

From source file:th.co.geniustree.dental.controller.LotController.java

@RequestMapping(value = "/loadlot/searchlot", method = RequestMethod.POST)
public Page<Lot> search(@RequestBody SearchData searchData, Pageable pageable) throws ParseException {
    String keyword = searchData.getKeyword();
    String searchBy = searchData.getSearchBy();
    Page<Lot> lots = null;/*from www. jav  a  2s  . com*/
    DateFormat df = new SimpleDateFormat("yyy-MM-dd", Locale.US);
    if ("Name".equals(searchBy)) {
        lots = lotService.searchByNameStaffReam(keyword, pageable);
    }
    if ("DateIn".equals(searchBy)) {
        Date keywordDate = df.parse(keyword);
        lots = lotService.searchByDateIn(keywordDate, pageable);
    }
    if ("DateOut".equals(searchBy)) {
        Date keywordDate = df.parse(keyword);
        lots = lotService.searchByDateOut(keywordDate, pageable);
    }
    return lots;
}

From source file:net.sourceforge.fenixedu.presentationTier.backBeans.manager.personManagement.ManagerFunctionsManagementBackingBean.java

@Override
public String associateNewFunction() throws FenixServiceException, ParseException {

    DateFormat format = new SimpleDateFormat("dd/MM/yyyy");
    Double credits = Double.valueOf(this.getCredits());

    Date beginDate_ = null, endDate_ = null;
    try {//from  w w w. jav  a2  s.  co m
        if (this.getBeginDate() != null) {
            beginDate_ = format.parse(this.getBeginDate());
        } else {
            setErrorMessage("error.notBeginDate");
            return "";
        }
        if (this.getEndDate() != null) {
            endDate_ = format.parse(this.getEndDate());
        } else {
            setErrorMessage("error.notEndDate");
            return "";
        }

        AssociateNewFunctionToPerson.runAssociateNewFunctionToPerson(this.getFunctionID(), this.getPersonID(),
                credits, YearMonthDay.fromDateFields(beginDate_), YearMonthDay.fromDateFields(endDate_));
        setErrorMessage("message.success");
        return "success";

    } catch (ParseException e) {
        setErrorMessage("error.date1.format");
    } catch (FenixServiceException e) {
        setErrorMessage(e.getMessage());
    } catch (DomainException e) {
        setErrorMessage(e.getMessage());
    }

    return "";
}

From source file:microsoft.exchange.webservices.data.misc.MapiTypeConverterMapEntry.java

/**
 * Change value to a value of compatible type.
 * <p/>/*from  www . j a v  a  2  s  .  c o  m*/
 * The type of a simple value should match exactly or be convertible to the
 * appropriate type. An array value has to be a single dimension (rank),
 * contain at least one value and contain elements that exactly match the
 * expected type. (We could relax this last requirement so that, for
 * example, you could pass an array of Int32 that could be converted to an
 * array of Double but that seems like overkill).
 *
 * @param value The value.
 * @return New value.
 * @throws Exception the exception
 */
public Object changeType(Object value) throws Exception {
    if (this.getIsArray()) {
        this.validateValueAsArray(value);
        return value;
    } else if (value.getClass() == this.getType()) {
        return value;
    } else {
        try {
            if (this.getType().isInstance(Integer.valueOf(0))) {
                Object o = null;
                o = Integer.parseInt(value + "");
                return o;
            } else if (this.getType().isInstance(new Date())) {
                DateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'");
                return df.parse(value + "");
            } else if (this.getType().isInstance(Boolean.valueOf(false))) {
                Object o = null;
                o = Boolean.parseBoolean(value + "");
                return o;
            } else if (this.getType().isInstance(String.class)) {
                return value;
            }
            return null;
        } catch (ClassCastException ex) {
            throw new ArgumentException(
                    String.format("The value '%s' of type %s can't be converted to a value of type %s.", "%s",
                            "%s", this.getType()),
                    ex);
        }
    }
}

From source file:com.salesmanager.core.module.impl.application.files.LocalFileImpl.java

public InputStream getFileInputStream(HttpServletRequest request) throws Exception {

    // parse token

    String fileid = request.getParameter("fileId");

    Map fileInfo = FileUtil.getFileDownloadFileTokens(fileid);

    String fileId = (String) fileInfo.get("ID");
    String date = (String) fileInfo.get("DATE");
    String merchantId = (String) fileInfo.get("MERCHANTID");

    // Compare the date
    Date today = new Date();
    DateFormat d = new SimpleDateFormat("yyyy-MM-dd");
    Date dt = null;// w  w  w. j  a  v  a2s. c o m

    dt = d.parse(date);

    if (dt.before(new Date(today.getTime()))) {
        // expired

        CoreException excpt = new CoreException(ErrorConstants.DELAY_EXPIRED);

        throw excpt;
        // String lbl =
        // LabelUtil.getInstance().getText("message.error.download.delayexpired1");

    }

    OrderService oservice = (OrderService) ServiceFactory.getService(ServiceFactory.OrderService);

    OrderProductDownload download = oservice.getOrderProductDownload(new Long(fileId));

    this.setFileName(download.getOrderProductFilename());

    int maxcount = conf.getInt("core.product.file.downloadmaxcount", 5);

    // String filename = "";

    FileHistory fh = oservice.getFileHistory(Integer.parseInt(merchantId), download.getFileId());

    if (fh == null) {
        log.warn("Trying to update non existing file history [attrid " + download.getFileId() + "][merchantid "
                + merchantId + "]");
    } else {
        int downloadcount = fh.getDownloadCount();
        int newcount = downloadcount + 1;
        fh.setDownloadCount(newcount);
        oservice.saveOrUpdateFileHistory(fh);
    }

    int downloadcount = download.getDownloadCount();
    if (downloadcount == maxcount) {
        OrderException oe = new OrderException("Maximum download reached",
                ErrorConstants.MAXIMUM_ORDER_PRODUCT_DOWNLOAD_REACHED);
        throw oe;

    }

    int newcount = downloadcount + 1;
    download.setDownloadCount(newcount);
    oservice.saveOrUpdateOrderProductDownload(download);

    //String downloadPath = conf.getString("core.product.file.filefolder");
    String downloadPath = FileUtil.getDownloadFilePath();

    File file = new File(downloadPath + "/" + merchantId + "/" + download.getOrderProductFilename());

    BufferedInputStream bis = new BufferedInputStream(new FileInputStream(file));

    return bis;
}