List of usage examples for org.joda.time.format DateTimeFormatter parseDateTime
public DateTime parseDateTime(String text)
From source file:org.finra.datagenerator.engine.scxml.tags.boundary.BoundaryDate.java
License:Apache License
/** * Grab random holiday from the equivalence class that falls between the two dates * * @param earliest the earliest date parameter as defined in the model * @param latest the latest date parameter as defined in the model * @return a holiday that falls between the dates */// www. jav a 2 s. c o m public String getRandomHoliday(String earliest, String latest) { String dateString = ""; DateTimeFormatter parser = ISODateTimeFormat.date(); DateTime earlyDate = parser.parseDateTime(earliest); DateTime lateDate = parser.parseDateTime(latest); List<Holiday> holidays = new LinkedList<>(); int min = Integer.parseInt(earlyDate.toString().substring(0, 4)); int max = Integer.parseInt(lateDate.toString().substring(0, 4)); int range = max - min + 1; int randomYear = (int) (Math.random() * range) + min; for (Holiday s : EquivalenceClassTransformer.HOLIDAYS) { holidays.add(s); } Collections.shuffle(holidays); for (Holiday holiday : holidays) { dateString = convertToReadableDate(holiday.forYear(randomYear)); if (toDate(dateString).after(toDate(earliest)) && toDate(dateString).before(toDate(latest))) { break; } } return dateString; }
From source file:org.finra.datagenerator.engine.scxml.tags.boundary.BoundaryDate.java
License:Apache License
/** * Given a year, month, and day, find the number of occurrences of that day in the month * * @param year the year//from w w w. j av a 2 s. c o m * @param month the month * @param day the day * @return the number of occurrences of the day in the month */ public int numOccurrences(int year, int month, int day) { DateTimeFormatter parser = ISODateTimeFormat.date(); DateTime date = parser.parseDateTime(year + "-" + month + "-" + "01"); Calendar cal = Calendar.getInstance(); cal.setTime(date.toDate()); GregorianChronology calendar = GregorianChronology.getInstance(); DateTimeField field = calendar.dayOfMonth(); int days = 0; int count = 0; int num = field.getMaximumValue(new LocalDate(year, month, day, calendar)); while (days < num) { if (cal.get(Calendar.DAY_OF_WEEK) == day) { count++; } date = date.plusDays(1); cal.setTime(date.toDate()); days++; } return count; }
From source file:org.finra.datagenerator.engine.scxml.tags.boundary.BoundaryDate.java
License:Apache License
/** * Convert the holiday format from EquivalenceClassTransformer into a date format * * @param holiday the date// ww w. j a va 2 s . c o m * @return a date String in the format yyyy-MM-dd */ public String convertToReadableDate(Holiday holiday) { DateTimeFormatter parser = ISODateTimeFormat.date(); if (holiday.isInDateForm()) { String month = Integer.toString(holiday.getMonth()).length() < 2 ? "0" + holiday.getMonth() : Integer.toString(holiday.getMonth()); String day = Integer.toString(holiday.getDayOfMonth()).length() < 2 ? "0" + holiday.getDayOfMonth() : Integer.toString(holiday.getDayOfMonth()); return holiday.getYear() + "-" + month + "-" + day; } else { /* * 5 denotes the final occurrence of the day in the month. Need to find actual * number of occurrences */ if (holiday.getOccurrence() == 5) { holiday.setOccurrence( numOccurrences(holiday.getYear(), holiday.getMonth(), holiday.getDayOfWeek())); } DateTime date = parser.parseDateTime(holiday.getYear() + "-" + holiday.getMonth() + "-" + "01"); Calendar calendar = Calendar.getInstance(); calendar.setTime(date.toDate()); int count = 0; while (count < holiday.getOccurrence()) { if (calendar.get(Calendar.DAY_OF_WEEK) == holiday.getDayOfWeek()) { count++; if (count == holiday.getOccurrence()) { break; } } date = date.plusDays(1); calendar.setTime(date.toDate()); } return date.toString().substring(0, 10); } }
From source file:org.fuin.ddd4j.ddd.JodaTransformer.java
License:Open Source License
@Override public final DateTime transform(final String value) { final String format = parameterInfo.getFormat(); final DateTimeFormatter dateTimeFormatter = DateTimeFormat.forPattern(format).withLocale(locale); return dateTimeFormatter.parseDateTime(value); }
From source file:org.gdg.frisbee.android.api.deserializer.DateTimeDeserializer.java
License:Apache License
@Override public DateTime deserialize(JsonElement jsonElement, Type type, JsonDeserializationContext jsonDeserializationContext) throws JsonParseException { //DateTimeFormatter fmt = DateTimeFormat.forPattern("YYYY-MM-dd'T'HH:mm:ssZZ"); //2013-05-15T16:30:00+02:00 DateTimeFormatter fmt = DateTimeFormat.forPattern("dd MMM YYYY HH:mm Z").withLocale(Locale.ENGLISH); // 04 Jul 2013 23:00 +0200 return fmt.parseDateTime(jsonElement.getAsJsonPrimitive().getAsString()); }
From source file:org.gdg.frisbee.android.cache.ModelCacheDateTimeDeserializer.java
License:Apache License
@Override public DateTime deserialize(JsonElement jsonElement, Type type, JsonDeserializationContext jsonDeserializationContext) throws JsonParseException { DateTimeFormatter fmt = DateTimeFormat.forPattern("YYYY-MM-dd'T'HH:mm:ss.SSS'Z'").withLocale(Locale.US); return fmt.parseDateTime(jsonElement.getAsJsonPrimitive().getAsString()); }
From source file:org.georchestra.analytics.StatisticsController.java
License:Open Source License
/** * Convert date from UTC to local configured timezone. This method is used to convert dates returns by database. * @param rawDate raw date from database with format : "2016-02-12 23" or "2016-02-12" or "2016-06" or "2016-02" * @return date in local timezone with hour * @throws ParseException if input date is not parsable *///w w w . j a va 2 s. c om private String convertUTCDateToLocal(String rawDate, GRANULARITY granularity) throws ParseException { DateTimeFormatter inputFormatter = null; DateTimeFormatter outputFormatter = null; switch (granularity) { case HOUR: inputFormatter = this.dbHourInputFormatter; outputFormatter = this.dbHourOutputFormatter; break; case DAY: inputFormatter = this.dbDayInputFormatter; outputFormatter = this.dbDayOutputFormatter; break; case WEEK: inputFormatter = this.dbWeekInputFormatter; outputFormatter = this.dbWeekOutputFormatter; break; case MONTH: inputFormatter = this.dbMonthInputFormatter; outputFormatter = this.dbMonthOutputFormatter; break; } DateTime localDatetime = inputFormatter.parseDateTime(rawDate); return outputFormatter.print(localDatetime.toInstant()); }
From source file:org.getwheat.harvest.library.dom.DomHelper.java
License:Apache License
/** * Converts the value of the specified tag to a Date object. * /* ww w.j av a 2 s . c o m*/ * @param element the Element to search * @param tag the XML Tag to find * @param parsePattern the Joda Time format to use for converting the Date * @return a Date object or null if not found */ public Date getDateValue(final Element element, final XmlTag tag, final String parsePattern) { Date value = null; final String nodeValue = getStringValue(element, tag); if (nodeValue != null) { final DateTimeFormatter formatter = DateTimeFormat.forPattern(parsePattern); try { value = formatter.parseDateTime(nodeValue).toDate(); } catch (Exception ex) { LOG.warn("", ex); } } return value; }
From source file:org.grails.plugins.elasticsearch.conversion.unmarshall.DomainClassUnmarshaller.java
License:Apache License
private Object unmarshallProperty(GrailsDomainClass domainClass, String propertyName, Object propertyValue, DefaultUnmarshallingContext unmarshallingContext) { // TODO : adapt behavior if the mapping option "component" or "reference" are set // below is considering the "component" behavior if (LOG.isDebugEnabled()) { //yeah, it's ugly to use + LOG.debug("Unmarshalling property " + propertyName + " with value " + propertyValue + " " + (propertyValue != null ? propertyValue.getClass().getName() : "")); }/* w ww .ja v a2s . com*/ SearchableClassPropertyMapping scpm = elasticSearchContextHolder.getMappingContext(domainClass) .getPropertyMapping(propertyName); Object parseResult = null; if (null == scpm) { // TODO: unhandled property exists in index LOG.error("Index contains a unhandled property which will be ignored. Property name" + propertyName + " with value " + propertyValue); return null; } if (null != scpm && propertyValue instanceof Map) { @SuppressWarnings({ "unchecked" }) Map<String, Object> data = (Map<String, Object>) propertyValue; // Handle cycle reference if (data.containsKey("ref")) { unmarshallingContext.addCycleRef(propertyValue); return null; } // Searchable reference. if (scpm.getReference() != null) { Class<?> refClass = scpm.getBestGuessReferenceType(); GrailsDomainClass refDomainClass = null; for (GrailsClass dClazz : grailsApplication.getArtefacts(DomainClassArtefactHandler.TYPE)) { if (dClazz.getClazz().equals(refClass)) { refDomainClass = (GrailsDomainClass) dClazz; break; } } if (refDomainClass == null) { throw new IllegalStateException("Found reference to non-domain class: " + refClass); } return unmarshallReference(refDomainClass, data, unmarshallingContext); } if (data.containsKey("class")) { // Embedded instance. if (!scpm.isComponent()) { // maybe ignore? throw new IllegalStateException("Property " + domainClass.getName() + "." + propertyName + " is not mapped as [component], but broken search hit found."); } GrailsDomainClass nestedDomainClass = (GrailsDomainClass) grailsApplication .getArtefact(DomainClassArtefactHandler.TYPE, (String) data.get("class")); if (domainClass != null) { // Unmarshall 'component' instance. if (!scpm.isComponent()) { throw new IllegalStateException("Object " + data.get("class") + " found in index, but [" + propertyName + "] is not mapped as component."); } parseResult = unmarshallDomain(nestedDomainClass, data.get("id"), data, unmarshallingContext); } } } else if (propertyValue instanceof Collection) { List<Object> results = new ArrayList<Object>(); int index = 0; for (Object innerValue : (Collection) propertyValue) { unmarshallingContext.getUnmarshallingStack().push(String.valueOf(index)); Object parseItem = unmarshallProperty(domainClass, propertyName, innerValue, unmarshallingContext); if (parseItem != null) { results.add(parseItem); } index++; unmarshallingContext.getUnmarshallingStack().pop(); } parseResult = results; } else if (scpm.getPropertyType() == Date.class) { //TODO: this is a quick fix as the unmarshalling of dates doesn't work DateTimeFormatter dtf = ISODateTimeFormat.dateOptionalTimeParser(); try { DateTime dateTime = dtf.parseDateTime(propertyValue.toString()); parseResult = dateTime.toDate(); } catch (Exception e) { LOG.error("Failed to parse the value " + propertyValue + "as date for property " + propertyName, e); } } else { // consider any custom property editors here. if (scpm.getConverter() != null) { LOG.debug("Using a converter for property" + propertyName); if (scpm.getConverter() instanceof Class) { try { PropertyEditor propertyEditor = (PropertyEditor) ((Class) scpm.getConverter()) .newInstance(); propertyEditor.setAsText((String) propertyValue); parseResult = propertyEditor.getValue(); } catch (Exception e) { throw new IllegalArgumentException( "Unable to unmarshall " + propertyName + " using " + scpm.getConverter(), e); } } } else if (scpm.getReference() != null) { // This is a reference and it MUST be null because it's not a Map. if (propertyValue != null) { throw new IllegalStateException("Found searchable reference which is not a Map: " + domainClass + "." + propertyName + " = " + propertyValue); } parseResult = null; } } if (parseResult != null) { LOG.debug("ParsedValue is ..." + parseResult); return parseResult; } else { LOG.debug("We will just return the same propery value as received..." + propertyValue); return propertyValue; } }
From source file:org.graylog.plugins.pipelineprocessor.functions.dates.ParseDate.java
License:Open Source License
@Override public DateTime evaluate(FunctionArgs args, EvaluationContext context, DateTimeZone timezone) { final String dateString = valueParam.required(args, context); final String pattern = patternParam.required(args, context); if (dateString == null || pattern == null) { return null; }/*from w w w.j av a2s. c om*/ final DateTimeFormatter formatter = DateTimeFormat.forPattern(pattern).withZone(timezone); return formatter.parseDateTime(dateString); }