Java Code Examples for org.apache.commons.lang3.time.FastDateFormat#getInstance()

The following examples show how to use org.apache.commons.lang3.time.FastDateFormat#getInstance() . 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: BaseDateTimeType.java    From org.hl7.fhir.core with Apache License 2.0 6 votes vote down vote up
/**
 * This method implements a datetime equality check using the rules as defined by FHIRPath (R2)
 *
 * Caveat: this implementation assumes local timezone for unspecified timezones 
 */
public Boolean equalsUsingFhirPathRules(BaseDateTimeType theOther) {
  TemporalPrecisionEnum mp = this.myPrecision == TemporalPrecisionEnum.MILLI ? TemporalPrecisionEnum.SECOND : this.myPrecision;
  TemporalPrecisionEnum op = theOther.myPrecision == TemporalPrecisionEnum.MILLI ? TemporalPrecisionEnum.SECOND : theOther.myPrecision;
  TemporalPrecisionEnum cp = (mp.compareTo(op) < 0) ? mp : op;
  FastDateFormat df = FastDateFormat.getInstance("yyyy-MM-dd'T'HH:mm:ss.SSS");
  String ms = df.format(this.getValue());
  String os = df.format(theOther.getValue());
  if (!sub(ms, cp.stringLength()).equals(sub(os, cp.stringLength()))) {
    return false;
  }
  if (mp != op) {
    return null;
  }
  if (this.myPrecision == TemporalPrecisionEnum.MILLI || theOther.myPrecision == TemporalPrecisionEnum.MILLI) {
    float mf = Float.parseFloat(ms.substring(17)); 
    float of = Float.parseFloat(os.substring(17));
    if (mf != of) {
      return false;
    }
  }
  return true;
}
 
Example 2
Source File: TestUtils.java    From hbase with Apache License 2.0 6 votes vote down vote up
private static RegionMetrics createRegionMetrics(String regionName, long readRequestCount,
  long filteredReadRequestCount, long writeRequestCount, Size storeFileSize,
  Size uncompressedStoreFileSize, int storeFileCount, Size memStoreSize, float locality,
  long compactedCellCount, long compactingCellCount, String lastMajorCompactionTime) {

  FastDateFormat df = FastDateFormat.getInstance("yyyy-MM-dd HH:mm:ss");
  try {
    return RegionMetricsBuilder.newBuilder(Bytes.toBytes(regionName))
      .setReadRequestCount(readRequestCount)
      .setFilteredReadRequestCount(filteredReadRequestCount)
      .setWriteRequestCount(writeRequestCount).setStoreFileSize(storeFileSize)
      .setUncompressedStoreFileSize(uncompressedStoreFileSize).setStoreFileCount(storeFileCount)
      .setMemStoreSize(memStoreSize).setDataLocality(locality)
      .setCompactedCellCount(compactedCellCount).setCompactingCellCount(compactingCellCount)
      .setLastMajorCompactionTimestamp(df.parse(lastMajorCompactionTime).getTime()).build();
  } catch (ParseException e) {
    throw new IllegalArgumentException(e);
  }
}
 
Example 3
Source File: DateCustom.java    From htmlunit with Apache License 2.0 6 votes vote down vote up
/**
 * Converts a date to a string, returning the "time" portion using the current locale's conventions.
 * @param context the JavaScript context
 * @param thisObj the scriptable
 * @param args the arguments passed into the method
 * @param function the function
 * @return converted string
 */
public static String toLocaleTimeString(
        final Context context, final Scriptable thisObj, final Object[] args, final Function function) {
    final String formatString;
    final BrowserVersion browserVersion = ((Window) thisObj.getParentScope()).getBrowserVersion();

    if (browserVersion.hasFeature(JS_DATE_WITH_LEFT_TO_RIGHT_MARK)) {
        // [U+200E] -> Unicode Character 'LEFT-TO-RIGHT MARK'
        formatString = "\u200Eh\u200E:\u200Emm\u200E:\u200Ess\u200E \u200Ea";
    }
    else {
        formatString = "h:mm:ss a";
    }
    final FastDateFormat format =  FastDateFormat.getInstance(formatString, getLocale(browserVersion));
    return format.format(getDateValue(thisObj));
}
 
Example 4
Source File: ColumnCast.java    From DataLink with Apache License 2.0 6 votes vote down vote up
static void init(final Configuration configuration) {
	StringCast.datetimeFormat = configuration.getString(
			"common.column.datetimeFormat", StringCast.datetimeFormat);
	StringCast.dateFormat = configuration.getString(
			"common.column.dateFormat", StringCast.dateFormat);
	StringCast.timeFormat = configuration.getString(
			"common.column.timeFormat", StringCast.timeFormat);
	StringCast.extraFormats = configuration.getList(
			"common.column.extraFormats", Collections.<String>emptyList(), String.class);

	StringCast.timeZone = configuration.getString("common.column.timeZone",
			StringCast.timeZone);
	StringCast.timeZoner = TimeZone.getTimeZone(StringCast.timeZone);

	StringCast.datetimeFormatter = FastDateFormat.getInstance(
			StringCast.datetimeFormat, StringCast.timeZoner);
	StringCast.dateFormatter = FastDateFormat.getInstance(
			StringCast.dateFormat, StringCast.timeZoner);
	StringCast.timeFormatter = FastDateFormat.getInstance(
			StringCast.timeFormat, StringCast.timeZoner);

	StringCast.encoding = configuration.getString("common.column.encoding",
			StringCast.encoding);
}
 
Example 5
Source File: BeanPanel.java    From syncope with Apache License 2.0 6 votes vote down vote up
@SuppressWarnings({ "unchecked", "rawtypes" })
private static FieldPanel buildSinglePanel(
    final Serializable bean, final Class<?> type, final String fieldName, final String id) {
    FieldPanel result = null;
    PropertyModel model = new PropertyModel(bean, fieldName);
    if (ClassUtils.isAssignable(Boolean.class, type)) {
        result = new AjaxCheckBoxPanel(id, fieldName, model);
    } else if (ClassUtils.isAssignable(Number.class, type)) {
        result = new AjaxSpinnerFieldPanel.Builder<>().build(
                id, fieldName, (Class<Number>) ClassUtils.resolvePrimitiveIfNecessary(type), model);
    } else if (Date.class.equals(type)) {
        result = new AjaxDateTimeFieldPanel(id, fieldName, model,
                FastDateFormat.getInstance(SyncopeConstants.DEFAULT_DATE_PATTERN));
    } else if (type.isEnum()) {
        result = new AjaxDropDownChoicePanel(id, fieldName, model).setChoices(
                List.of(type.getEnumConstants()));
    }

    // treat as String if nothing matched above
    if (result == null) {
        result = new AjaxTextFieldPanel(id, fieldName, model);
    }

    result.hideLabel();
    return result;
}
 
Example 6
Source File: DateCustom.java    From HtmlUnit-Android with Apache License 2.0 6 votes vote down vote up
/**
 * Converts a date to a string, returning the "date" portion using the operating system's locale's conventions.
 * @param context the JavaScript context
 * @param thisObj the scriptable
 * @param args the arguments passed into the method
 * @param function the function
 * @return converted string
 */
public static String toLocaleDateString(
        final Context context, final Scriptable thisObj, final Object[] args, final Function function) {
    final String formatString;
    final BrowserVersion browserVersion = ((Window) thisObj.getParentScope()).getBrowserVersion();

    if (browserVersion.hasFeature(JS_DATE_WITH_LEFT_TO_RIGHT_MARK)) {
        // [U+200E] -> Unicode Character 'LEFT-TO-RIGHT MARK'
        formatString = "\u200EM\u200E/\u200Ed\u200E/\u200Eyyyy";
    }
    else if (browserVersion.hasFeature(JS_DATE_LOCALE_DATE_SHORT)) {
        formatString = "M/d/yyyy";
    }
    else {
        formatString = "EEEE, MMMM dd, yyyy";
    }
    final FastDateFormat format =  FastDateFormat.getInstance(formatString, getLocale(browserVersion));
    return format.format(getDateValue(thisObj));
}
 
Example 7
Source File: CleanUpScheduler.java    From feeyo-redisproxy with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
/**
 * return current date time by specified hour:minute
 * 
 * @param plan format: hh:mm
 */
public static Date getCurrentDateByPlan(String plan, String pattern) {
	try {
		FastDateFormat format = FastDateFormat.getInstance(pattern);
		Date end = format.parse(plan);
		Calendar today = Calendar.getInstance();
		end = DateUtils.setYears(end, (today.get(Calendar.YEAR)));
		end = DateUtils.setMonths(end, today.get(Calendar.MONTH));
		end = DateUtils.setDays(end, today.get(Calendar.DAY_OF_MONTH));
		return end;
	} catch (Exception e) {
		throw new RuntimeException( e );
	}
}
 
Example 8
Source File: GetChangelistsDateRangeTest.java    From p4ic4idea with Apache License 2.0 5 votes vote down vote up
private String oneWeekBefore() {
    FastDateFormat dateFormat = FastDateFormat.getInstance("@yyyy/MM/dd");

    Calendar now = Calendar.getInstance();
    now.add(Calendar.WEEK_OF_YEAR, -1);

    return dateFormat.format(now);
}
 
Example 9
Source File: GetChangelistsDateRangeTest.java    From p4ic4idea with Apache License 2.0 5 votes vote down vote up
private String oneWeekBefore() {
    FastDateFormat dateFormat = FastDateFormat.getInstance("@yyyy/MM/dd");

    Calendar now = Calendar.getInstance();
    now.add(Calendar.WEEK_OF_YEAR, -1);

    return dateFormat.format(now);
}
 
Example 10
Source File: DateFormat.java    From kylin with Apache License 2.0 5 votes vote down vote up
public static FastDateFormat getDateFormat(String datePattern) {
    FastDateFormat r = formatMap.get(datePattern);
    if (r == null) {
        r = FastDateFormat.getInstance(datePattern, TimeZone.getTimeZone("GMT")); // NOTE: this must be GMT to calculate epoch date correctly
        formatMap.put(datePattern, r);
    }
    return r;
}
 
Example 11
Source File: MapperDate.java    From ambari-logsearch with Apache License 2.0 5 votes vote down vote up
@Override
public boolean init(LogFeederProps logFeederProps, String inputDesc, String fieldName, String mapClassCode, MapFieldDescriptor mapFieldDescriptor) {
  init(inputDesc, fieldName, mapClassCode);
  
  String targetDateFormat = ((MapDateDescriptor)mapFieldDescriptor).getTargetDatePattern();
  String srcDateFormat = ((MapDateDescriptor)mapFieldDescriptor).getSourceDatePattern();
  if (StringUtils.isEmpty(targetDateFormat)) {
    logger.fatal("Date format for map is empty. " + this);
  } else {
    logger.info("Date mapper format is " + targetDateFormat);

    if (targetDateFormat.equalsIgnoreCase("epoch")) {
      isEpoch = true;
      return true;
    } else {
      try {
        targetDateFormatter = FastDateFormat.getInstance(targetDateFormat);
        if (!StringUtils.isEmpty(srcDateFormat)) {
          srcDateFormatter = FastDateFormat.getInstance(srcDateFormat);
        }
        return true;
      } catch (Throwable ex) {
        logger.fatal("Error creating date format. format=" + targetDateFormat + ". " + this.toString());
      }
    } 
  }
  return false;
}
 
Example 12
Source File: CleanUpScheduler.java    From vjtools with Apache License 2.0 5 votes vote down vote up
/**
 * return current date time by specified hour:minute
 * 
 * @param plan format: hh:mm
 */
public static Date getCurrentDateByPlan(String plan, String pattern) {
	try {
		FastDateFormat format = FastDateFormat.getInstance(pattern);
		Date end = format.parse(plan);
		Calendar today = Calendar.getInstance();
		end = DateUtils.setYears(end, (today.get(Calendar.YEAR)));
		end = DateUtils.setMonths(end, today.get(Calendar.MONTH));
		end = DateUtils.setDays(end, today.get(Calendar.DAY_OF_MONTH));
		return end;
	} catch (Exception e) {
		throw ExceptionUtil.unchecked(e);
	}
}
 
Example 13
Source File: DateFormat.java    From kylin-on-parquet-v2 with Apache License 2.0 5 votes vote down vote up
public static FastDateFormat getDateFormat(String datePattern) {
    FastDateFormat r = formatMap.get(datePattern);
    if (r == null) {
        r = FastDateFormat.getInstance(datePattern, TimeZone.getTimeZone("GMT")); // NOTE: this must be GMT to calculate epoch date correctly
        formatMap.put(datePattern, r);
    }
    return r;
}
 
Example 14
Source File: RegionModeStrategy.java    From hbase with Apache License 2.0 4 votes vote down vote up
private Record createRecord(ServerMetrics serverMetrics, RegionMetrics regionMetrics,
  long lastReportTimestamp) {

  Record.Builder builder = Record.builder();

  String regionName = regionMetrics.getNameAsString();
  builder.put(Field.REGION_NAME, regionName);

  String namespaceName = "";
  String tableName = "";
  String region = "";
  String startKey = "";
  String startCode = "";
  String replicaId = "";
  try {
    byte[][] elements = RegionInfo.parseRegionName(regionMetrics.getRegionName());
    TableName tn = TableName.valueOf(elements[0]);
    namespaceName = tn.getNamespaceAsString();
    tableName = tn.getQualifierAsString();
    startKey = Bytes.toStringBinary(elements[1]);
    startCode = Bytes.toString(elements[2]);
    replicaId = elements.length == 4 ?
      Integer.valueOf(Bytes.toString(elements[3])).toString() : "";
    region = RegionInfo.encodeRegionName(regionMetrics.getRegionName());
  } catch (IOException ignored) {
  }

  builder.put(Field.NAMESPACE, namespaceName);
  builder.put(Field.TABLE, tableName);
  builder.put(Field.START_CODE, startCode);
  builder.put(Field.REPLICA_ID, replicaId);
  builder.put(Field.REGION, region);
  builder.put(Field.START_KEY, startKey);
  builder.put(Field.REGION_SERVER, serverMetrics.getServerName().toShortString());
  builder.put(Field.LONG_REGION_SERVER, serverMetrics.getServerName().getServerName());

  RequestCountPerSecond requestCountPerSecond = requestCountPerSecondMap.get(regionName);
  if (requestCountPerSecond == null) {
    requestCountPerSecond = new RequestCountPerSecond();
    requestCountPerSecondMap.put(regionName, requestCountPerSecond);
  }
  requestCountPerSecond.refresh(lastReportTimestamp, regionMetrics.getReadRequestCount(),
    regionMetrics.getFilteredReadRequestCount(), regionMetrics.getWriteRequestCount());

  builder.put(Field.READ_REQUEST_COUNT_PER_SECOND,
    requestCountPerSecond.getReadRequestCountPerSecond());
  builder.put(Field.FILTERED_READ_REQUEST_COUNT_PER_SECOND,
      requestCountPerSecond.getFilteredReadRequestCountPerSecond());
  builder.put(Field.WRITE_REQUEST_COUNT_PER_SECOND,
    requestCountPerSecond.getWriteRequestCountPerSecond());
  builder.put(Field.REQUEST_COUNT_PER_SECOND,
    requestCountPerSecond.getRequestCountPerSecond());

  builder.put(Field.STORE_FILE_SIZE, regionMetrics.getStoreFileSize());
  builder.put(Field.UNCOMPRESSED_STORE_FILE_SIZE, regionMetrics.getUncompressedStoreFileSize());
  builder.put(Field.NUM_STORE_FILES, regionMetrics.getStoreFileCount());
  builder.put(Field.MEM_STORE_SIZE, regionMetrics.getMemStoreSize());
  builder.put(Field.LOCALITY, regionMetrics.getDataLocality());

  long compactingCellCount = regionMetrics.getCompactingCellCount();
  long compactedCellCount = regionMetrics.getCompactedCellCount();
  float compactionProgress = 0;
  if  (compactedCellCount > 0) {
    compactionProgress = 100 * ((float) compactedCellCount / compactingCellCount);
  }

  builder.put(Field.COMPACTING_CELL_COUNT, compactingCellCount);
  builder.put(Field.COMPACTED_CELL_COUNT, compactedCellCount);
  builder.put(Field.COMPACTION_PROGRESS, compactionProgress);

  FastDateFormat df = FastDateFormat.getInstance("yyyy-MM-dd HH:mm:ss");
  long lastMajorCompactionTimestamp = regionMetrics.getLastMajorCompactionTimestamp();

  builder.put(Field.LAST_MAJOR_COMPACTION_TIME,
    lastMajorCompactionTimestamp == 0 ? "" : df.format(lastMajorCompactionTimestamp));

  return builder.build();
}
 
Example 15
Source File: CachingDateFormatter.java    From vjtools with Apache License 2.0 4 votes vote down vote up
public CachingDateFormatter(String pattern) {
	this(FastDateFormat.getInstance(pattern));
}
 
Example 16
Source File: DateStrValueConvert.java    From search-commons with Apache License 2.0 4 votes vote down vote up
public DateStrValueConvert(String pattern) {
    this(FastDateFormat.getInstance(pattern));
}
 
Example 17
Source File: DateFormat.java    From kylin-on-parquet-v2 with Apache License 2.0 4 votes vote down vote up
private static String formatToStrWithTimeZone(TimeZone timeZone, long mills, String pattern){
    FastDateFormat dateFormat =  FastDateFormat.getInstance(pattern, timeZone);
    return dateFormat.format(new Date(mills));
}
 
Example 18
Source File: DateFormat.java    From kylin with Apache License 2.0 4 votes vote down vote up
private static String formatToStrWithTimeZone(TimeZone timeZone, long mills, String pattern){
    FastDateFormat dateFormat =  FastDateFormat.getInstance(pattern, timeZone);
    return dateFormat.format(new Date(mills));
}
 
Example 19
Source File: DateFormType.java    From flowable-engine with Apache License 2.0 4 votes vote down vote up
public DateFormType(String datePattern) {
    this.datePattern = datePattern;
    this.dateFormat = FastDateFormat.getInstance(datePattern);
}
 
Example 20
Source File: DateUtil.java    From phoenix with Apache License 2.0 4 votes vote down vote up
public static Format getDateFormatter(String pattern, String timeZoneID) {
    return DateUtil.DEFAULT_DATE_FORMAT.equals(pattern) && DateUtil.DEFAULT_TIME_ZONE_ID.equals(timeZoneID)
            ? DateUtil.DEFAULT_DATE_FORMATTER
            : FastDateFormat.getInstance(pattern, getTimeZone(timeZoneID));
}