List of usage examples for java.text DateFormat parse
public Date parse(String source) throws ParseException
From source file:io.seldon.importer.articles.dynamicextractors.FirstElementAttrValueDateWithFormatDynamicExtractor.java
@Override public String extract(AttributeDetail attributeDetail, String url, Document articleDoc) throws Exception { String attrib_value = null;//www . jav a2 s. c o m String dateFormatString = null; if ((attributeDetail.extractor_args != null) && (attributeDetail.extractor_args.size() >= 3)) { String cssSelector = attributeDetail.extractor_args.get(0); dateFormatString = attributeDetail.extractor_args.get(1); Element element = articleDoc.select(cssSelector).first(); if (StringUtils.isNotBlank(cssSelector)) { int arg_count = 0; for (String value_name : attributeDetail.extractor_args) { if (arg_count > 1) { // skip the first one, its the cssSelector, and second thats the Date format if (element != null && element.attr(value_name) != null) { attrib_value = element.attr(value_name); if (StringUtils.isNotBlank(attrib_value)) { break; } } } arg_count++; } } } if ((attrib_value != null) && (dateFormatString != null)) { String pubtext = attrib_value; SimpleDateFormat dateFormatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); DateFormat df = new SimpleDateFormat(dateFormatString, Locale.ENGLISH); Date result = null; try { result = df.parse(pubtext); } catch (ParseException e) { logger.info("Failed to parse date with format [" + dateFormatString + "] " + pubtext); } if (result != null) { String attrib_value_orig = attrib_value; attrib_value = dateFormatter.format(result); String msg = "Extracted date [" + attrib_value_orig + "] - > [" + attrib_value + "]"; logger.info(msg); } else { logger.error("Failed to parse date " + pubtext); attrib_value = null; } } return attrib_value; }
From source file:itdelatrisu.opsu.downloads.servers.OsuMirrorServer.java
/** * Returns a formatted date string from a raw date. * @param s the raw date string (e.g. "2015-05-14T23:38:47Z") * @return the formatted date, or the raw string if it could not be parsed *///from w w w. j av a 2 s. c om private String formatDate(String s) { try { DateFormat f = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'"); f.setTimeZone(TimeZone.getTimeZone("UTC")); Date d = f.parse(s); DateFormat fmt = new SimpleDateFormat("d MMM yyyy HH:mm:ss"); return fmt.format(d); } catch (ParseException e) { return s; } }
From source file:com.eryansky.common.utils.DateUtil.java
@SuppressWarnings("unchecked") public static <T extends java.util.Date> T parse(String dateString, String dateFormat, Class<T> targetResultType) { if (StringUtils.isEmpty(dateString)) return null; DateFormat df = new SimpleDateFormat(dateFormat); try {//from w ww .j a v a 2 s. c om long time = df.parse(dateString).getTime(); java.util.Date t = targetResultType.getConstructor(long.class).newInstance(time); return (T) t; } catch (ParseException e) { String errorInfo = "cannot use dateformat:" + dateFormat + " parse datestring:" + dateString; throw new IllegalArgumentException(errorInfo, e); } catch (Exception e) { throw new IllegalArgumentException("error targetResultType:" + targetResultType.getName(), e); } }
From source file:com.mobileman.projecth.business.patient.PatientQuestionAnswerServiceTest.java
/** * @throws Exception//from w w w.j a v a 2 s . c o m */ @Test public void saveAnswer() throws Exception { Question question = questionService.findAll().get(0); Answer answer = question.getQuestionType().getAnswers().get(0); User patient = userService.findUserByLogin("sysuser1"); assertNotNull(patient); DateFormat dateFormat = DateFormat.getDateInstance(); Date logDate = dateFormat.parse("1.1.2011"); int count = patientQuestionAnswerService.findAll().size(); patientQuestionAnswerService.saveAnswer(patient.getId(), question.getId(), answer.getId(), "custom", logDate); assertEquals(count + 1, patientQuestionAnswerService.findAll().size()); }
From source file:controllers.MailController.java
public Result sendMail() { JsonNode json = request().body().asJson(); if (json == null) { return Common.badRequestWrapper("mail not sent, expecting Json data"); }/* w ww . j a v a 2s . co m*/ String fromUserMail = json.path("fromUserMail").asText(); String toUserMail = json.path("toUserMail").asText(); User fromUser = userRepository.findByEmail(fromUserMail); User toUser = userRepository.findByEmail(toUserMail); if (fromUser == null || toUser == null) { Map<String, String> map = new HashMap<>(); map.put("error", "No Access!"); String error = new Gson().toJson(map); return ok(error); } String mailTitle = json.path("mailTitle").asText(); String mailContent = json.path("mailContent").asText(); String dateString = json.path("mailDate").asText(); DateFormat dateFormat = new SimpleDateFormat("dd-MM-yyyy"); Date mailDate = new Date(); try { mailDate = dateFormat.parse(dateString); } catch (ParseException e) { e.printStackTrace(); } Mail mail = new Mail(fromUserMail, toUserMail, mailTitle, mailContent, mailDate); mailRepository.save(mail); return created(new Gson().toJson("success")); }
From source file:com.strider.datadefender.extensions.BiographicFunctions.java
/** * Generates random 9-digit social insurance number * @return String//from ww w.j a va 2 s .c o m * @throws java.text.ParseException */ public java.sql.Date randomBirthDate() throws java.text.ParseException { final GregorianCalendar gc = new GregorianCalendar(); final int year = randBetween(1900, 2016); gc.set(GregorianCalendar.YEAR, year); final int dayOfYear = randBetween(1, gc.getActualMaximum(GregorianCalendar.DAY_OF_YEAR)); gc.set(GregorianCalendar.DAY_OF_YEAR, dayOfYear); final String birthDate = prependZero(gc.get(GregorianCalendar.DAY_OF_MONTH)) + "-" + prependZero(gc.get(GregorianCalendar.MONTH) + 1) + "-" + gc.get(GregorianCalendar.YEAR); log.debug("BirthDate:[" + birthDate + "]"); final DateFormat format = new SimpleDateFormat("dd-MM-yyyy", Locale.US); final java.sql.Date date = new java.sql.Date(format.parse(birthDate).getTime()); log.debug("Generated BirthDate:[" + date.toString() + "]"); return date; }
From source file:io.seldon.importer.articles.dynamicextractors.FirstElementAttrValueDateDynamicExtractor.java
@Override public String extract(AttributeDetail attributeDetail, String url, Document articleDoc) throws Exception { String attrib_value = null;/* w w w. j ava 2s . co m*/ if ((attributeDetail.extractor_args != null) && (attributeDetail.extractor_args.size() >= 2)) { String cssSelector = attributeDetail.extractor_args.get(0); Element element = articleDoc.select(cssSelector).first(); if (StringUtils.isNotBlank(cssSelector)) { int arg_count = 0; for (String value_name : attributeDetail.extractor_args) { if (arg_count > 0) { // skip the first one, its the cssSelector if (element != null && element.attr(value_name) != null) { attrib_value = element.attr(value_name); if (StringUtils.isNotBlank(attrib_value)) { break; } } } arg_count++; } } } if (attrib_value != null) { String pubtext = attrib_value; SimpleDateFormat dateFormatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); DateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss", Locale.ENGLISH); Date result = null; try { result = df.parse(pubtext); } catch (ParseException e) { logger.info("Failed to parse date withUTC format " + pubtext); } // try a simpler format df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.ENGLISH); try { result = df.parse(pubtext); } catch (ParseException e) { logger.info("Failed to parse date " + pubtext); } if (result != null) { attrib_value = dateFormatter.format(result); } else { logger.error("Failed to parse date " + pubtext); } } return attrib_value; }
From source file:com.aegiswallet.utils.WalletUtils.java
public static List<ECKey> readKeys(@Nonnull final BufferedReader in) throws IOException { try {/*from w ww. j a va 2s .c o m*/ final DateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); final List<ECKey> keys = new LinkedList<ECKey>(); while (true) { final String line = in.readLine(); if (line == null) break; // eof if (line.trim().isEmpty() || line.charAt(0) == '#') continue; // skip comment final String[] parts = line.split(" "); final ECKey key = new DumpedPrivateKey(Constants.NETWORK_PARAMETERS, parts[0]).getKey(); key.setCreationTimeSeconds( parts.length >= 2 ? format.parse(parts[1]).getTime() / DateUtils.SECOND_IN_MILLIS : 0); keys.add(key); } return keys; } catch (final AddressFormatException x) { throw new IOException("cannot read keys", x); } catch (final ParseException x) { throw new IOException("cannot read keys", x); } }
From source file:com.googlecode.jsfFlex.component.ext.AbstractFlexUIDateChooser.java
@Override public void decode(FacesContext context) { super.decode(context); java.util.Map<String, String> requestMap = context.getExternalContext().getRequestParameterMap(); String selectedDateId = getId() + SELECTED_DATE_ID_APPENDED; String selectedDateUpdateVal = requestMap.get(selectedDateId); if (selectedDateUpdateVal != null && selectedDateUpdateVal.length() > 0) { /*/* w w w. j a v a 2 s .com*/ * HACK: Since ActionScript returns date in format of "Thu Aug 23 00:00:00 GMT-0700 2009" * and "EEE MMM dd HH:mm:ss zZ yyyy" pattern doesn't seem to match it within SimpleDateFormat, * place a space between z + Z */ int dashIndex = selectedDateUpdateVal.indexOf("-"); if (dashIndex != -1) { selectedDateUpdateVal = selectedDateUpdateVal.substring(0, dashIndex) + " " + selectedDateUpdateVal.substring(dashIndex); } Calendar instance = Calendar.getInstance(); try { DateFormat dateFormat = new SimpleDateFormat(DATE_FORMAT_DEFAULT); dateFormat.setLenient(true); instance.setTime(dateFormat.parse(selectedDateUpdateVal)); setSelectedDate(instance); setSubmittedValue(selectedDateUpdateVal); } catch (ParseException parsingException) { setValid(false); context.addMessage(getId(), new FacesMessage("Parsing exception for value : " + selectedDateUpdateVal)); _log.error("Parsing exception for value : " + selectedDateUpdateVal, parsingException); } } }
From source file:org.openmrs.module.urandumodule.web.controller.UranduModuleManageController.java
@RequestMapping(value = "/module/urandumodule/submitForm", method = RequestMethod.GET) public String submitForm(ModelMap model, @RequestParam(value = "family_name", required = false) String family_name, @RequestParam(value = "middle_name", required = false) String middle_name, @RequestParam(value = "given_name", required = false) String given_name, @RequestParam(value = "dob", required = false) String dob, @RequestParam(value = "id_number", required = false) String id_number, @RequestParam(value = "gender", required = false) String gender, @RequestParam(value = "address", required = false) Integer address, @RequestParam(value = "postal_code", required = false) Integer postal_code, @RequestParam(value = "town", required = false) String town, @RequestParam(value = "country", required = false) String country) { Person person = new Person(); PersonName personName = new PersonName(); personName.setFamilyName(family_name); personName.setMiddleName(middle_name); personName.setGivenName(given_name); //name added to person person.addName(personName);//from w w w . j av a 2 s .c om PersonAddress personAddress = new PersonAddress(); personAddress.setAddress1(address.toString()); personAddress.setCityVillage(town); personAddress.setCountry(country); personAddress.setPostalCode(postal_code.toString()); //address added to person person.addAddress(personAddress); //gender added to person person.setGender(gender); DateFormat dateFormat = new SimpleDateFormat("dd-mm-yyyy"); Date birthday = null; try { birthday = dateFormat.parse(dob); } catch (ParseException e) { e.printStackTrace(); } person.setBirthdate(birthday); /*person.setBirthdate();*/ Patient patient = new Patient(person); PatientService patientService = Context.getPatientService(); //Identifier issues PatientIdentifier openmrsId = new PatientIdentifier(); String TARGET_ID_KEY = "urandumodule.idType"; String TARGET_ID = Context.getAdministrationService().getGlobalProperty(TARGET_ID_KEY); PatientIdentifierType openmrsIdType = patientService.getPatientIdentifierTypeByName(TARGET_ID); openmrsId.setIdentifier(id_number); openmrsId.setDateCreated(new Date()); openmrsId.setLocation(Context.getLocationService().getDefaultLocation()); openmrsId.setIdentifierType(openmrsIdType); PatientIdentifierValidator.validateIdentifier(openmrsId); patient.addIdentifier(openmrsId); //saving the patient if (!patientService.isIdentifierInUseByAnotherPatient(openmrsId)) { patientService.savePatient(patient); model.addAttribute("save_success", "Patient successfully saved"); return "redirect:patientForm.form"; } else { model.addAttribute("save_failed", "Patient not saved : duplicate id number"); return "redirect:patientForm.form"; } }