List of usage examples for org.joda.time.format DateTimeFormatter parseDateTime
public DateTime parseDateTime(String text)
From source file:net.javahispano.jsignalwb.jsignalmonitor.TimeRepresentation.java
License:Apache License
/** * Recibe una cadena de caracteres con formato <code>HH:mm:ss[.SSS] * [dd/MM/yyyy]</code>, siendo optativo el contenido entre corchetes, y * devuelve el tiempo que ha transcurrido desde 00:00:00 01/01/1970 * hasta ese instante en milisegundos./*from w ww . j a v a2s . c om*/ * * @param time fecha como cadena de caracteres. * @param date true si la cadena de caracteres contiene dia a mes y * anho, false en caso contrario. * @param hour true si la cadena de caracteres contiene horas, minutos * y segundos, false en caso contrario. * @param milisec true si la cadena de caracteres contienen * milisegundos, false en caso contrario. * @return milisegundos transcurridos desde la fecha base. */ public static long stringToMillis(String time, boolean date, boolean hour, boolean milisec) { DateTimeFormatter fmt = getFormatter(date, hour, milisec); DateTime dt = fmt.parseDateTime(time); //System.out.println(dt.toString(fmt)); return dt.getMillis(); }
From source file:net.longfalcon.newsj.util.DateUtil.java
License:Open Source License
public static DateTime parseNNTPDate(String dateString) { DateTime dateTime = null;/*from w w w .j a va 2s. c o m*/ try { dateTime = RFC_dateFormatter.parseDateTime(dateString); } catch (IllegalArgumentException e) { // do nothing } int i = 0; while (dateTime == null && i < _dateFormats.length) { try { DateTimeFormatter fmt = DateTimeFormat.forPattern(_dateFormats[i]); dateTime = fmt.parseDateTime(dateString); } catch (IllegalArgumentException e) { // do nothing } i++; } i = 0; while (dateTime == null && i < _dateFormats.length) { try { DateFormat javaFormatter = new SimpleDateFormat(_dateFormats[i]); Date date = javaFormatter.parse(dateString); dateTime = new DateTime(date); } catch (Exception e) { // do nothing } i++; } if (dateTime == null) { _log.error(String.format("Unable to parse date string \'%s\'", dateString)); dateTime = new DateTime(); } return dateTime; }
From source file:net.opentsdb.odata.OpenTSDBProducer.java
License:Open Source License
/** * Convert a string to a unix timestamp// ww w . j ava2s.c o m * * @param dateTimeParameter * formatted as "2011/05/26-10:59:00" * or relative format * formatted as 12m-ago, 30d-dago or 2y-ago * @return seconds since epoch (aka unix timestamp) */ private long parseDateTimeParameter(String dateTimeParameter) { assert (dateTimeParameter != null); String regex = "^(\\d+)([yhwsmd])-ago$"; Pattern pattern = Pattern.compile(regex); Matcher matcher = pattern.matcher(dateTimeParameter); // use relative date if (matcher.find()) return parseRelativeDateTime(matcher.group(1), matcher.group(2)); DateTimeFormatter fmt = DateTimeFormat.forPattern("yyyy/MM/dd-HH:mm:ss"); DateTime dt = fmt.parseDateTime(dateTimeParameter); return dt.getMillis() / 1000; /* only interested in seconds */ }
From source file:net.ripe.rpki.commons.FixedDateRule.java
License:BSD License
private static long convertDateTimeStringToMillis(String yyyymmdd) { DateTimeFormatter dateTimeParser = new DateTimeFormatterBuilder().appendYear(4, 4).appendMonthOfYear(2) .appendDayOfMonth(2).toFormatter().withZone(DateTimeZone.UTC); return dateTimeParser.parseDateTime(yyyymmdd).getMillis(); }
From source file:net.schweerelos.parrot.model.NodeWrapper.java
License:Open Source License
private String createToolTip(ParrotModel model) { if (!isOntResource()) { return ""; }/*from w ww . ja va2s . c om*/ OntResource resource = getOntResource(); if (!resource.isIndividual() || resource.isProperty()) { return ""; } StringBuilder text = new StringBuilder(); // use extracted model to speed up reasoning OntModel ontModel = model.getOntModel(); ModelExtractor extractor = new ModelExtractor(ontModel); extractor.setSelector(StatementType.PROPERTY_VALUE); Model eModel = extractor.extractModel(); Resource eResource = eModel.getResource(resource.getURI()); StmtIterator props = eResource.listProperties(); while (props.hasNext()) { Statement statement = props.nextStatement(); Property pred = statement.getPredicate(); if (!pred.isURIResource()) { continue; } OntProperty ontPred = ontModel.getOntProperty(pred.getURI()); if (ontPred == null) { continue; } if (ParrotModelHelper.showTypeAsSecondary(ontModel, ontPred)) { // anything in the tooltip yet? if so, add line break text.append(text.length() > 0 ? "<br>" : ""); // put in extracted predicate label text.append(extractLabel(ontPred)); text.append(" "); RDFNode object = statement.getObject(); if (object.isLiteral()) { Literal literal = (Literal) object.as(Literal.class); String lexicalForm = literal.getLexicalForm(); if (literal.getDatatype().equals(XSDDatatype.XSDdateTime)) { DateTimeFormatter parser = ISODateTimeFormat.dateTimeParser(); DateTime dateTime = parser.parseDateTime(lexicalForm); DateTimeFormatterBuilder formatter = new DateTimeFormatterBuilder() .appendMonthOfYearShortText().appendLiteral(' ').appendDayOfMonth(1) .appendLiteral(", ").appendYear(4, 4).appendLiteral(", ").appendHourOfHalfday(1) .appendLiteral(':').appendMinuteOfHour(2).appendHalfdayOfDayText() .appendLiteral(" (").appendTimeZoneName().appendLiteral(", UTC") .appendTimeZoneOffset("", true, 1, 1).appendLiteral(')'); String prettyDateTime = formatter.toFormatter().print(dateTime); text.append(prettyDateTime); } else { text.append(lexicalForm); } } else if (object.isURIResource()) { OntResource ontObject = ontModel.getOntResource((Resource) object.as(Resource.class)); if (ontObject == null) { continue; } text.append(extractLabel(ontObject)); } } } // surround with html tags text.insert(0, "<html>"); text.append("</html>"); String result = text.toString(); if (result.equals("<html></html>")) { result = ""; } return result; }
From source file:net.sf.jacclog.service.analyzer.commands.internal.AnalyzeLogEntriesShellCommand.java
License:Apache License
private void analyzeEntries() { if (service != null) { final DateTimeFormatter format = DateTimeFormat.forPattern("yyyyMMdd"); final DateTime from = format.parseDateTime(this.from); final DateTime to = (this.to != null) ? format.parseDateTime(this.to) : from.plusDays(1); final Interval interval = new Interval(from, to); final Period period = interval.toPeriod(); final StringBuffer buffer = new StringBuffer(); buffer.append("Analyse the log entries from '"); buffer.append(from.toString()).append('\''); buffer.append(" to '").append(to); // print the period final String space = " "; buffer.append("'. The period includes "); final PeriodFormatter dateFormat = new PeriodFormatterBuilder().appendYears() .appendSuffix(" year", " years").appendSeparator(space).appendMonths() .appendSuffix(" month", " months").appendSeparator(space).appendWeeks() .appendSuffix(" week", " weeks").appendSeparator(space).appendDays() .appendSuffix(" day", " days").appendSeparator(space).appendHours() .appendSuffix(" hour", " hours").appendSeparator(space).appendMinutes() .appendSuffix(" minute", " minutes").appendSeparator(space).toFormatter(); dateFormat.printTo(buffer, period); buffer.append('.'); System.out.println(buffer.toString()); final long maxResults = service.count(interval); if (maxResults > 0) { int maxCount = 0; if (proceed(maxResults)) { final long startTime = System.currentTimeMillis(); final LogEntryAnalysisResult result = analyzerService.analyze(interval).toResult(); final Map<UserAgentInfo, AtomicInteger> stats = result.getUserAgentInfos(); System.out.println("User agent information count: " + stats.size()); String name;//w w w . j a va 2s.c o m String osName; int count; for (final Entry<UserAgentInfo, AtomicInteger> entry : stats.entrySet()) { name = entry.getKey().getName(); osName = entry.getKey().getOsName(); count = entry.getValue().get(); maxCount += count; System.out.println(name + " (" + osName + ") \t" + count); } System.out.println("Sum: " + maxCount); final long elapsedTime = System.currentTimeMillis() - startTime; final Period p = new Period(elapsedTime); System.out.println("Total processing time: " + p.toString(FORMATTER)); } } else { System.out.println("There is nothing to analyze."); } } }
From source file:net.simonvt.cathode.api.util.TimeUtils.java
License:Apache License
public static long getMillis(String iso) { if (iso != null) { final int length = iso.length(); DateTimeFormatter fmt; if (length <= 20) { fmt = ISODateTimeFormat.dateTimeNoMillis(); } else {/*w w w . j a v a 2 s.c o m*/ fmt = ISODateTimeFormat.dateTime(); } return fmt.parseDateTime(iso).getMillis(); } return 0L; }
From source file:net.solarnetwork.node.setup.impl.DefaultSetupService.java
License:Open Source License
@Override public NetworkAssociationDetails decodeVerificationCode(String verificationCode) throws InvalidVerificationCodeException { log.debug("Decoding verification code {}", verificationCode); NetworkAssociationDetails details = new NetworkAssociationDetails(); try {/*ww w.j a va 2 s .co m*/ JavaBeanXmlSerializer helper = new JavaBeanXmlSerializer(); InputStream in = new GZIPInputStream( new Base64InputStream(new ByteArrayInputStream(verificationCode.getBytes()))); Map<String, Object> result = helper.parseXml(in); // Get the host server String hostName = (String) result.get(VERIFICATION_CODE_HOST_NAME); if (hostName == null) { // Use the default log.debug("Property {} not found in verfication code", VERIFICATION_CODE_HOST_NAME); throw new InvalidVerificationCodeException("Missing host"); } details.setHost(hostName); // Get the host port String hostPort = (String) result.get(VERIFICATION_CODE_HOST_PORT); if (hostPort == null) { log.debug("Property {} not found in verfication code", VERIFICATION_CODE_HOST_PORT); throw new InvalidVerificationCodeException("Missing port"); } try { details.setPort(Integer.valueOf(hostPort)); } catch (NumberFormatException e) { throw new InvalidVerificationCodeException("Invalid host port value: " + hostPort, e); } // Get the confirmation Key String confirmationKey = (String) result.get(VERIFICATION_CODE_CONFIRMATION_KEY); if (confirmationKey == null) { throw new InvalidVerificationCodeException("Missing confirmation code"); } details.setConfirmationKey(confirmationKey); // Get the identity key String identityKey = (String) result.get(VERIFICATION_CODE_IDENTITY_KEY); if (identityKey == null) { throw new InvalidVerificationCodeException("Missing identity key"); } details.setIdentityKey(identityKey); // Get the user name String userName = (String) result.get(VERIFICATION_CODE_USER_NAME_KEY); if (userName == null) { throw new InvalidVerificationCodeException("Missing username"); } details.setUsername(userName); // Get the expiration String expiration = (String) result.get(VERIFICATION_CODE_EXPIRATION_KEY); if (expiration == null) { throw new InvalidVerificationCodeException( VERIFICATION_CODE_EXPIRATION_KEY + " not found in verification code: " + verificationCode); } try { DateTimeFormatter fmt = ISODateTimeFormat.dateTime(); DateTime expirationDate = fmt.parseDateTime(expiration); details.setExpiration(expirationDate.toDate()); } catch (IllegalArgumentException e) { throw new InvalidVerificationCodeException("Invalid expiration date value", e); } // Get the TLS setting String forceSSL = (String) result.get(VERIFICATION_CODE_FORCE_TLS); details.setForceTLS(forceSSL == null ? false : Boolean.valueOf(forceSSL)); return details; } catch (InvalidVerificationCodeException e) { throw e; } catch (Exception e) { // Runtime/IO errors can come from webFormGetForBean throw new InvalidVerificationCodeException( "Error while trying to decode verfication code: " + verificationCode, e); } }
From source file:net.solarnetwork.util.JodaDateFormatEditor.java
License:Open Source License
@Override public void setAsText(String text) throws IllegalArgumentException { IllegalArgumentException iae = null; // try patterns one at a time, if all fail to parse then throw exception for (DateTimeFormatter df : this.dateFormatters) { try {/*from w ww . j a va2 s.com*/ DateTime dt = df.parseDateTime(text); Object val = dt; switch (this.parseMode) { case LocalDate: val = dt.toLocalDate(); break; case LocalTime: val = dt.toLocalTime(); break; default: // leave as DateTime } setValue(val); iae = null; break; } catch (IllegalArgumentException e) { iae = e; } } if (iae != null) { throw iae; } }
From source file:net.vexelon.currencybg.app.utils.DateTimeUtils.java
License:Open Source License
/** * * @param dateTime//w ww.ja v a2s. co m * @return */ public static Date parseStringToDate(String dateTime) { DateTimeFormatter parse = ISODateTimeFormat.dateTimeParser(); DateTime dateTimeHere = parse.parseDateTime(dateTime); Date dateNew = dateTimeHere.toDate(); return dateNew; }