org.joda.time.format.DateTimeFormatter Java Examples

The following examples show how to use org.joda.time.format.DateTimeFormatter. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: Partial.java    From astor with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Gets a formatter suitable for the fields in this partial.
 * <p>
 * If there is no appropriate ISO format, null is returned.
 * This method may return a formatter that does not display all the
 * fields of the partial. This might occur when you have overlapping
 * fields, such as dayOfWeek and dayOfMonth.
 *
 * @return a formatter suitable for the fields in this partial, null
 *  if none is suitable
 */
public DateTimeFormatter getFormatter() {
    DateTimeFormatter[] f = iFormatter;
    if (f == null) {
        if (size() == 0) {
            return null;
        }
        f = new DateTimeFormatter[2];
        try {
            List<DateTimeFieldType> list = new ArrayList<DateTimeFieldType>(Arrays.asList(iTypes));
            f[0] = ISODateTimeFormat.forFields(list, true, false);
            if (list.size() == 0) {
                f[1] = f[0];
            }
        } catch (IllegalArgumentException ex) {
            // ignore
        }
        iFormatter = f;
    }
    return f[0];
}
 
Example #2
Source File: ControlFileModel.java    From datasync with MIT License 6 votes vote down vote up
private boolean canParseDateTime(Object value, String[] dateTimeFormats){
    if (value == null || value.toString().isEmpty())
        return true;

    for (String format : dateTimeFormats) {
        try {
            if (format.startsWith("ISO"))
                ISODateTimeFormat.dateTime().parseDateTime((String) value);
            else {
                DateTimeFormatter dateStringFormat = DateTimeFormat.forPattern(format);
                dateStringFormat.parseDateTime((String) value);
            }
            //If we make it here, then we know that we've been able to parse the value
            return true;
        } catch (Exception e) {
            continue;
        }
    }
    return false;
}
 
Example #3
Source File: TimeUtil.java    From sakai with Educational Community License v2.0 6 votes vote down vote up
public String getDateTimeWithTimezoneConversion(Date dateToConvert) {
    if (dateToConvert == null) {
        return null;
    }
    DateTime dt = new DateTime(dateToConvert);
    DateTimeFormatter fmt = ISODateTimeFormat.yearMonthDay();
    DateTimeFormatter fmtTime = ISODateTimeFormat.hourMinuteSecond();

    // If the client browser is in a different timezone than server, need to modify date
    if (m_client_timezone !=null && m_server_timezone!=null && !m_client_timezone.hasSameRules(m_server_timezone)) {
      DateTimeZone dateTimeZone = DateTimeZone.forTimeZone(m_client_timezone);
      fmt = fmt.withZone(dateTimeZone);
      fmtTime = fmtTime.withZone(dateTimeZone);
    }
    return dt.toString(fmt) + " " + dt.toString(fmtTime);
}
 
Example #4
Source File: Interval.java    From program-ab with GNU Lesser General Public License v3.0 6 votes vote down vote up
public static int getDaysBetween(final String date1, final String date2, String format){
    try {
        final DateTimeFormatter fmt =
                DateTimeFormat
                        .forPattern(format)
                        .withChronology(
                                LenientChronology.getInstance(
                                        GregorianChronology.getInstance()));
        return Days.daysBetween(
                fmt.parseDateTime(date1),
                fmt.parseDateTime(date2)
        ).getDays();
    } catch (Exception ex) {
        ex.printStackTrace();
        return 0;
    }
}
 
Example #5
Source File: Elixir_0040_t.java    From coming with MIT License 6 votes vote down vote up
/**
 * Output the date in an appropriate ISO8601 format.
 * <p>
 * This method will output the partial in one of two ways.
 * If {@link #getFormatter()}
 * <p>
 * If there is no appropriate ISO format a dump of the fields is output
 * via {@link #toStringList()}.
 * 
 * @return ISO8601 formatted string
 */
public String toString() {
    DateTimeFormatter[] f = iFormatter;
    if (f == null) {
        getFormatter();
        f = iFormatter;
        if (f == null) {
            return toStringList();
        }
    }
    DateTimeFormatter f1 = f[1];
    if (f1 == null) {
        return toStringList();
    }
    return f1.print(this);
}
 
Example #6
Source File: Utils.java    From incubator-gobblin with Apache License 2.0 6 votes vote down vote up
/**
 * Helper method for getting a value containing CURRENTDAY-1 or CURRENTHOUR-1 in the form yyyyMMddHHmmss
 * @param value
 * @param timezone
 * @return
 */
public static long getLongWithCurrentDate(String value, String timezone) {
  if (Strings.isNullOrEmpty(value)) {
    return 0;
  }

  DateTime time = getCurrentTime(timezone);
  DateTimeFormatter dtFormatter = DateTimeFormat.forPattern(CURRENT_DATE_FORMAT).withZone(time.getZone());
  if (value.toUpperCase().startsWith(CURRENT_DAY)) {
    return Long
        .parseLong(dtFormatter.print(time.minusDays(Integer.parseInt(value.substring(CURRENT_DAY.length() + 1)))));
  }
  if (value.toUpperCase().startsWith(CURRENT_HOUR)) {
    return Long
        .parseLong(dtFormatter.print(time.minusHours(Integer.parseInt(value.substring(CURRENT_HOUR.length() + 1)))));
  }
  return Long.parseLong(value);
}
 
Example #7
Source File: CustomConfigRuntimeTest.java    From activiti6-boot2 with Apache License 2.0 6 votes vote down vote up
@Test
@DmnDeploymentAnnotation(resources = "org/activiti/dmn/engine/test/deployment/post_custom_expression_function_expression_1.dmn")
public void executeDecision_post_custom_expression_function() {

    DmnEngine dmnEngine = activitiRule1.getDmnEngine();
    DmnRuleService ruleService = dmnEngine.getDmnRuleService();

    Map<String, Object> processVariablesInput = new HashMap<String, Object>();

    DateTimeFormatter dateTimeFormatter = DateTimeFormat.forPattern("yyyy-MM-dd");
    LocalDate localDate = dateTimeFormatter.parseLocalDate("2015-09-18");

    processVariablesInput.put("input1", localDate.toDate());
    RuleEngineExecutionResult result = ruleService.executeDecisionByKey("decision", processVariablesInput);
    Assert.assertNotNull(result);
    Assert.assertSame(result.getResultVariables().get("output1").getClass(), String.class);
    Assert.assertEquals(result.getResultVariables().get("output1"), "test2");
}
 
Example #8
Source File: LookbackPartitionFilterGenerator.java    From incubator-gobblin with Apache License 2.0 6 votes vote down vote up
@Override
public String getFilter(HiveDataset hiveDataset) {

  if (isValidConfig()) {
    String partitionColumn = this.prop.getProperty(PARTITION_COLUMN);
    Period lookback = Period.parse(this.prop.getProperty(LOOKBACK));
    DateTimeFormatter formatter = DateTimeFormat.forPattern(this.prop.getProperty(DATETIME_FORMAT));

    DateTime limitDate = (new DateTime()).minus(lookback);

    String partitionFilter = String.format("%s >= \"%s\"", partitionColumn, formatter.print(limitDate));
    log.info(String.format("Getting partitions for %s using partition filter %s", ((hiveDataset == null) ? "null" :  hiveDataset.getTable()
        .getCompleteName()), partitionFilter));
    return partitionFilter;
  } else {
    log.error(LookbackPartitionFilterGenerator.class.getName()
        + " requires the following properties " + Arrays.toString(new String[]{PARTITION_COLUMN, LOOKBACK, DATETIME_FORMAT}));

    return null;
  }
}
 
Example #9
Source File: BPMNUserSubstitutionTestCase.java    From product-ei with Apache License 2.0 6 votes vote down vote up
private int updateSubstitute(String substitute, String assignee, DateTime start, DateTime end)
        throws JSONException, IOException {
    JSONObject payload = new JSONObject();
    if (substitute != null) {
        payload.put("substitute", substitute);
    }

    DateTimeFormatter isoFormat = ISODateTimeFormat.dateTime();
    if (start != null) {
        payload.put("startTime", isoFormat.print(start));
    }

    if (end != null) {
        payload.put("endTime", isoFormat.print(end));
    }

    HttpResponse response = BPMNTestUtils.putRequest(backEndUrl + SUBSTITUTE_URL + "/" + assignee, payload);
    return response.getStatusLine().getStatusCode();
}
 
Example #10
Source File: TimeUtil.java    From sakai with Educational Community License v2.0 6 votes vote down vote up
public String getIsoDateWithLocalTime(Date dateToConvert) {
    if (dateToConvert == null) {
        return null;
    }
    DateTime dt = new DateTime(dateToConvert);
    DateTimeFormatter fmt = ISODateTimeFormat.yearMonthDay();
    DateTimeFormatter localFmt = fmt.withLocale(new ResourceLoader().getLocale());
    DateTimeFormatter fmtTime = DateTimeFormat.shortTime();
    DateTimeFormatter localFmtTime = fmtTime.withLocale(new ResourceLoader().getLocale());

    // If the client browser is in a different timezone than server, need to modify date
    if (m_client_timezone !=null && m_server_timezone!=null && !m_client_timezone.hasSameRules(m_server_timezone)) {
      DateTimeZone dateTimeZone = DateTimeZone.forTimeZone(m_client_timezone);
      localFmt = localFmt.withZone(dateTimeZone);
      localFmtTime = localFmtTime.withZone(dateTimeZone);
    }
    return dt.toString(localFmt) + " " + dt.toString(localFmtTime);
}
 
Example #11
Source File: Cardumen_00189_s.java    From coming with MIT License 5 votes vote down vote up
/**
 * Gets a printer/parser for managing the offset id formatting.
 * 
 * @return the formatter
 */
private static synchronized DateTimeFormatter offsetFormatter() {
    if (cOffsetFormatter == null) {
        cOffsetFormatter = new DateTimeFormatterBuilder()
            .appendTimeZoneOffset(null, true, 2, 4)
            .toFormatter();
    }
    return cOffsetFormatter;
}
 
Example #12
Source File: GitLabComment.java    From scava with Eclipse Public License 2.0 5 votes vote down vote up
private static java.util.Date convertStringToDate(String isoDate) {
	
	isoDate = isoDate.replaceAll("\"", "");
	DateTimeFormatter parser = ISODateTimeFormat.dateTimeParser();
	DateTime date = parser.parseDateTime(isoDate);
	return date.toDate();
}
 
Example #13
Source File: JodaDateMidnightConverter.java    From projectforge-webapp with GNU General Public License v3.0 5 votes vote down vote up
Object parse(final String data) {
  try {
    final DateTimeFormatter parseFormat = DateTimeFormat.forPattern(ISO_FORMAT);
    final DateTime date = parseFormat.withZone(DateTimeZone.UTC).parseDateTime(data);
    final DateMidnight dateMidnight = date.toDateMidnight();
    return dateMidnight;
  } catch (final Exception ex) {
    log.error("Can't parse DateMidnight: " + data);
    return new DateMidnight();
  }
}
 
Example #14
Source File: Cardumen_00239_s.java    From coming with MIT License 5 votes vote down vote up
/**
 * Gets a printer/parser for managing the offset id formatting.
 * 
 * @return the formatter
 */
private static synchronized DateTimeFormatter offsetFormatter() {
    if (cOffsetFormatter == null) {
        cOffsetFormatter = new DateTimeFormatterBuilder()
            .appendTimeZoneOffset(null, true, 2, 4)
            .toFormatter();
    }
    return cOffsetFormatter;
}
 
Example #15
Source File: CalendarUtil.java    From sakai with Educational Community License v2.0 5 votes vote down vote up
static String getLocalPMString(DateTime now) {
	//we need an PM date
	DateTime dt = now.withTimeAtStartOfDay().plusHours(14);
	Locale locale = new ResourceLoader("calendar").getLocale();
	DateTimeFormatter df = new DateTimeFormatterBuilder().appendHalfdayOfDayText().toFormatter().withLocale(locale);
	return df.print(dt);
}
 
Example #16
Source File: SelfServiceDataSetCRUD.java    From Knowage-Server with GNU Affero General Public License v3.0 5 votes vote down vote up
private boolean isADate(JSONObject jsonConf, IDataStore dataStore, int columnIndex) throws JSONException {
	String dateFormat = jsonConf.get(DataSetConstants.FILE_DATE_FORMAT).toString();
	for (int i = 0; i < Math.min(10, dataStore.getRecordsCount()); i++) {
		IRecord record = dataStore.getRecordAt(i);
		IField field = record.getFieldAt(columnIndex);
		Object value = field.getValue();
		if (value instanceof Date) {
			if (value instanceof Timestamp)
				return false;

			// it's already a Date, skip the check
			continue;
		}
		try {
			// JDK 8 version
			/*
			 * DateTimeFormatter formatter = DateTimeFormatter.ofPattern(dateFormat); LocalDate localDate = LocalDate.parse((String) field.getValue(),
			 * formatter); Date date = Date.from(localDate.atStartOfDay(ZoneId.systemDefault()).toInstant());
			 */
			DateTimeFormatter formatter = DateTimeFormat.forPattern(dateFormat);
			LocalDate localDate = LocalDate.parse((String) field.getValue(), formatter);
			localDate.toDate();

		} catch (Exception ex) {
			logger.debug(field.getValue() + " is not a date");
			return false;
		}
	}
	return true;
}
 
Example #17
Source File: JodaTimeHelperTest.java    From SimpleFlatMapper with MIT License 5 votes vote down vote up
@Test
public void testFormattersFromFormatter() {
    final DateTimeFormatter yyyyMMdd = JodaTimeHelper.getDateTimeFormatters(DATE_TIME_FORMATTER_SUPPLIER)[0];
    final long instant = System.currentTimeMillis();
    assertEquals(DateTimeFormat.forPattern("MMddyyyy").print(instant), yyyyMMdd.print(instant));
    assertEquals(DateTimeZone.getDefault(), yyyyMMdd.getZone());

}
 
Example #18
Source File: CMSExtensions.java    From fenixedu-cms with GNU Lesser General Public License v3.0 5 votes vote down vote up
@Override
public Object apply(Object input, Map<String, Object> args) {
    if (input instanceof DateTime) {
        String pattern = (String) args.get("format");
        if (pattern == null) {
            pattern = "MMMM d, Y, H:m";
        }
        DateTimeFormatter fmt = DateTimeFormat.forPattern(pattern);
        return fmt.print((DateTime) input);
    }
    return "";
}
 
Example #19
Source File: DateTimeTypeAdapter.java    From devicehive-java with Apache License 2.0 5 votes vote down vote up
@Override
public JsonElement serialize(DateTime json,
                             Type typeOfSrc,
                             JsonSerializationContext context) {
    final DateTimeFormatter formatter = DateTimeFormat.forPattern(iso_pattern).withZoneUTC();
    return new JsonPrimitive(formatter.print(json));
}
 
Example #20
Source File: UtilsTest.java    From amforeas with GNU General Public License v3.0 5 votes vote down vote up
@Test
public void testIsTime () {
    DateTimeFormatter df = ISODateTimeFormat.time();
    DateTime date = df.parseDateTime("12:35:45.000Z");
    assertEquals(date, AmforeasUtils.isTime("12:35:45.000Z"));
    assertEquals(date, AmforeasUtils.isTime("123545.000Z"));
    assertNull(AmforeasUtils.isTime(""));
    assertNull(AmforeasUtils.isTime(null));
    assertNull(AmforeasUtils.isTime("2011-01-19"));
    assertNull(AmforeasUtils.isTime("20110119"));
    assertNull(AmforeasUtils.isTime("22:00:00"));
    assertNull(AmforeasUtils.isTime("2011-12-11T12:35:45.200Z"));
}
 
Example #21
Source File: JodaDateConverter.java    From projectforge-webapp with GNU General Public License v3.0 5 votes vote down vote up
/**
 * @param locale ignored, locale of PFUserContext is used instead.
 * @see org.apache.wicket.datetime.DateConverter#convertToString(java.lang.Object, java.util.Locale)
 * @see DateTimeFormatter#getFormattedDate(Object)
 */
@Override
public String convertToString(final DateMidnight value, final Locale locale)
{
  if (value == null) {
    return null;
  }
  final DateTimeFormatter formatter = getDateTimeFormatter(userDateFormat, locale);
  return formatter.print(value);
}
 
Example #22
Source File: CalendarUtil.java    From sakai with Educational Community License v2.0 5 votes vote down vote up
static String getLocalPMString(DateTime now) {
	//we need an PM date
	DateTime dt = now.withTimeAtStartOfDay().plusHours(14);
	Locale locale = new ResourceLoader("calendar").getLocale();
	DateTimeFormatter df = new DateTimeFormatterBuilder().appendHalfdayOfDayText().toFormatter().withLocale(locale);
	return df.print(dt);
}
 
Example #23
Source File: TimeAwareRecursiveCopyableDataset.java    From incubator-gobblin with Apache License 2.0 5 votes vote down vote up
private boolean isDatePatternHourly(String datePattern) {
  DateTimeFormatter formatter = DateTimeFormat.forPattern(datePattern);
  LocalDateTime refDateTime = new LocalDateTime(2017, 01, 01, 10, 0, 0);
  String refDateTimeString = refDateTime.toString(formatter);
  LocalDateTime refDateTimeAtStartOfDay = refDateTime.withHourOfDay(0);
  String refDateTimeStringAtStartOfDay = refDateTimeAtStartOfDay.toString(formatter);
  return !refDateTimeString.equals(refDateTimeStringAtStartOfDay);
}
 
Example #24
Source File: DatePlusYears.java    From levelup-java-examples with Apache License 2.0 5 votes vote down vote up
@Test
public void add_years_to_date_in_java8() {

	LocalDateTime superBowlXLV = LocalDateTime.of(2011, Month.FEBRUARY, 6,
			0, 0);
	LocalDateTime fortyNinersSuck = superBowlXLV.plusYears(2);

	java.time.format.DateTimeFormatter formatter = java.time.format.DateTimeFormatter
			.ofPattern("MM/dd/yyyy HH:mm:ss S");

	logger.info(superBowlXLV.format(formatter));
	logger.info(fortyNinersSuck.format(formatter));

	assertTrue(fortyNinersSuck.isAfter(superBowlXLV));
}
 
Example #25
Source File: DateUtil.java    From flink-learning with Apache License 2.0 5 votes vote down vote up
/**
 * 判断时间是否有效
 *
 * @param value
 * @param formatter
 * @return
 */
public static Boolean isValidDate(String value, DateTimeFormatter formatter) {
    try {
        formatter.parseDateTime(value);
        return true;
    } catch (Exception e) {
        return false;
    }
}
 
Example #26
Source File: ParseTime.java    From h2o-2 with Apache License 2.0 5 votes vote down vote up
public static String listTimezones() {
  DateTimeFormatter offsetFormatter = new DateTimeFormatterBuilder().appendTimeZoneOffset(null, true, 2, 4).toFormatter();
  Set<String> idSet = DateTimeZone.getAvailableIDs();
  Map<String, String> tzMap = new TreeMap();
  Iterator<String>  it = idSet.iterator();
  String id, cid, offset, key, output;
  DateTimeZone tz;
  int i = 0;
  long millis = System.currentTimeMillis();


  // collect canonical and alias IDs into a map
  while (it.hasNext()) {
    id = it.next();
    tz = DateTimeZone.forID(id);
    cid = tz.getID();
    offset = offsetFormatter.withZone(tz).print(tz.getStandardOffset(millis));
    key = offset + " " + cid;
    if (id == cid) { // Canonical ID
      if (!tzMap.containsKey(key)) tzMap.put(key, "");
    }  else {// alias ID
      if (!tzMap.containsKey(key)) tzMap.put(key, id);
      else tzMap.put(key,  tzMap.get(key) + ", " + id);
    }
  }

  // assemble result
  output = "StandardOffset CanonicalID, Aliases\n";
  for (Map.Entry<String, String> e : tzMap.entrySet())
    output += e.getKey() + e.getValue()+"\n";

  return output;
}
 
Example #27
Source File: UtilsTest.java    From amforeas with GNU General Public License v3.0 5 votes vote down vote up
@Test
public void testIsDateTime () {
    DateTimeFormatter df = ISODateTimeFormat.dateTime();
    DateTime date = df.parseDateTime("2011-12-11T12:35:45.200+01:00");
    assertEquals(date, AmforeasUtils.isDateTime("2011-12-11T12:35:45.200+01:00"));
    assertNull(AmforeasUtils.isDateTime("2011-12-11 22:00:00"));
    assertNull(AmforeasUtils.isDateTime(""));
    assertNull(AmforeasUtils.isDateTime(null));
    assertNull(AmforeasUtils.isDateTime("2011-01-19"));
    assertNull(AmforeasUtils.isDateTime("20110119"));
    assertNull(AmforeasUtils.isDateTime("22:00:00"));
    assertNull(AmforeasUtils.isDateTime("12:35:45.200+01:00"));
}
 
Example #28
Source File: DateUtilTests.java    From flink-learning with Apache License 2.0 5 votes vote down vote up
@Test
public void testWithTimeAtEndOfDay() {
    DateTimeFormatter dtf =
            DateTimeFormat.forPattern("yyyy-MM-dd HH:mm:ss");
    Date date = new Date(1557961199000L);
    DateTime dt = new DateTime(1557961199000L);

    Assert.assertEquals("2019-05-15 23:59:59",
            DateUtil.withTimeAtEndOfDay(date, dtf));
    Assert.assertEquals("2019-05-15 23:59:59",
            DateUtil.withTimeAtEndOfDay(dt, dtf));
}
 
Example #29
Source File: Joda.java    From crate with Apache License 2.0 5 votes vote down vote up
public static FormatDateTimeFormatter getStrictStandardDateFormatter() {
    // 2014/10/10
    DateTimeFormatter shortFormatter = new DateTimeFormatterBuilder()
            .appendFixedDecimal(DateTimeFieldType.year(), 4)
            .appendLiteral('/')
            .appendFixedDecimal(DateTimeFieldType.monthOfYear(), 2)
            .appendLiteral('/')
            .appendFixedDecimal(DateTimeFieldType.dayOfMonth(), 2)
            .toFormatter()
            .withZoneUTC();

    // 2014/10/10 12:12:12
    DateTimeFormatter longFormatter = new DateTimeFormatterBuilder()
            .appendFixedDecimal(DateTimeFieldType.year(), 4)
            .appendLiteral('/')
            .appendFixedDecimal(DateTimeFieldType.monthOfYear(), 2)
            .appendLiteral('/')
            .appendFixedDecimal(DateTimeFieldType.dayOfMonth(), 2)
            .appendLiteral(' ')
            .appendFixedSignedDecimal(DateTimeFieldType.hourOfDay(), 2)
            .appendLiteral(':')
            .appendFixedSignedDecimal(DateTimeFieldType.minuteOfHour(), 2)
            .appendLiteral(':')
            .appendFixedSignedDecimal(DateTimeFieldType.secondOfMinute(), 2)
            .toFormatter()
            .withZoneUTC();

    DateTimeFormatterBuilder builder = new DateTimeFormatterBuilder().append(longFormatter.withZone(DateTimeZone.UTC).getPrinter(), new DateTimeParser[]{longFormatter.getParser(), shortFormatter.getParser(), new EpochTimeParser(true)});

    return new FormatDateTimeFormatter("yyyy/MM/dd HH:mm:ss||yyyy/MM/dd||epoch_millis", builder.toFormatter().withZone(DateTimeZone.UTC), Locale.ROOT);
}
 
Example #30
Source File: JodaDateTimeFormatAnnotationFormatterFactory.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
@Override
public Printer<?> getPrinter(DateTimeFormat annotation, Class<?> fieldType) {
	DateTimeFormatter formatter = getFormatter(annotation, fieldType);
	if (ReadablePartial.class.isAssignableFrom(fieldType)) {
		return new ReadablePartialPrinter(formatter);
	}
	else if (ReadableInstant.class.isAssignableFrom(fieldType) || Calendar.class.isAssignableFrom(fieldType)) {
		// assumes Calendar->ReadableInstant converter is registered
		return new ReadableInstantPrinter(formatter);
	}
	else {
		// assumes Date->Long converter is registered
		return new MillisecondInstantPrinter(formatter);
	}
}