org.apache.commons.lang3.time.FastDateFormat Java Examples

The following examples show how to use org.apache.commons.lang3.time.FastDateFormat. 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: 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 #2
Source File: StandardJsonLoggerExceptionTest.java    From slf4j-json-logger with Apache License 2.0 6 votes vote down vote up
@Before
public void setup() {
  this.slf4jLogger = mock(org.slf4j.Logger.class);

  // Use a special GSON configuration that throws exceptions at the right time for the test.
  this.gson = new GsonBuilder().registerTypeAdapterFactory(new TestTypeAdapterFactory()).create();

  this.formatter = FastDateFormat.getInstance(dateFormatString);

  logger = new StandardJsonLogger(slf4jLogger, formatter, gson, null, null, null) {
    @Override
    public void log() {
      logMessage = formatMessage("INFO");
    }

  };
}
 
Example #3
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 #4
Source File: ListeFilme.java    From MLib with GNU General Public License v3.0 6 votes vote down vote up
public synchronized String genDate() {
    // Tag, Zeit in lokaler Zeit wann die Filmliste erstellt wurde
    // in der Form "dd.MM.yyyy, HH:mm"
    String ret;
    String date;
    if (metaDaten[ListeFilme.FILMLISTE_DATUM_GMT_NR].isEmpty()) {
        // noch eine alte Filmliste
        ret = metaDaten[ListeFilme.FILMLISTE_DATUM_NR];
    } else {
        date = metaDaten[ListeFilme.FILMLISTE_DATUM_GMT_NR];
        SimpleDateFormat sdf_ = new SimpleDateFormat(DATUM_ZEIT_FORMAT);
        sdf_.setTimeZone(new SimpleTimeZone(SimpleTimeZone.UTC_TIME, "UTC"));
        Date filmDate = null;
        try {
            filmDate = sdf_.parse(date);
        } catch (ParseException ignored) {
        }
        if (filmDate == null) {
            ret = metaDaten[ListeFilme.FILMLISTE_DATUM_GMT_NR];
        } else {
            FastDateFormat formatter = FastDateFormat.getInstance(DATUM_ZEIT_FORMAT);
            ret = formatter.format(filmDate);
        }
    }
    return ret;
}
 
Example #5
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 #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 "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 #7
Source File: DatenFilm.java    From MLib with GNU General Public License v3.0 6 votes vote down vote up
private void checkDatum(String datum, String fehlermeldung) {
  datum = datum.trim();
  if (datum.contains(".") && datum.length() == 10) {
    try {
      Date filmDate = FastDateFormat.getInstance("dd.MM.yyyy").parse(datum);
      if (filmDate.getTime() < 0) {
        //Datum vor 1970
        Log.errorLog(923012125, "Unsinniger Wert: [" + datum + "] " + fehlermeldung);
      } else {
        arr[FILM_DATUM] = datum;
      }
    } catch (Exception ex) {
      Log.errorLog(794630593, ex);
      Log.errorLog(946301596, '[' + datum + "] " + fehlermeldung);
    }
  }
}
 
Example #8
Source File: DateUtils.java    From frpMgr with MIT License 6 votes vote down vote up
/**
	 * 获取某月有几天
	 * @param date 日期
	 * @return 天数
	 */
	public static int getMonthHasDays(Date date){
//		String yyyyMM = new SimpleDateFormat("yyyyMM").format(date);
		String yyyyMM = FastDateFormat.getInstance("yyyyMM").format(date);
		String year = yyyyMM.substring(0, 4);
		String month = yyyyMM.substring(4, 6);
		String day31 = ",01,03,05,07,08,10,12,";
		String day30 = "04,06,09,11";
		int day = 0;
		if (day31.contains(month)) {
			day = 31;
		} else if (day30.contains(month)) {
			day = 30;
		} else {
			int y = Integer.parseInt(year);
			if ((y % 4 == 0 && (y % 100 != 0)) || y % 400 == 0) {
				day = 29;
			} else {
				day = 28;
			}
		}
		return day;
	}
 
Example #9
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 #10
Source File: IcalUtils.java    From openmeetings with Apache License 2.0 6 votes vote down vote up
/**
 * Adapted from DateUtils to support Timezones, and parse ical dates into {@link java.util.Date}.
 * Note: Replace FastDateFormat to java.time, when shifting to Java 8 or higher.
 *
 * @param str      Date representation in String.
 * @param patterns Patterns to parse the date against
 * @param inTimeZone Timezone of the Date.
 * @return <code>java.util.Date</code> representation of string or
 * <code>null</code> if the Date could not be parsed.
 */
public Date parseDate(String str, String[] patterns, TimeZone inTimeZone) {
	FastDateFormat parser;
	Locale locale = WebSession.get().getLocale();

	TimeZone timeZone = str.endsWith("Z") ? TimeZone.getTimeZone("UTC") : inTimeZone;

	ParsePosition pos = new ParsePosition(0);
	for (String pattern : patterns) {
		parser = FastDateFormat.getInstance(pattern, timeZone, locale);
		pos.setIndex(0);
		Date date = parser.parse(str, pos);
		if (date != null && pos.getIndex() == str.length()) {
			return date;
		}
	}
	log.error("Unable to parse the date: {} at {}", str, -1);
	return null;
}
 
Example #11
Source File: CachingDateFormatter.java    From vjtools with Apache License 2.0 5 votes vote down vote up
public CachingDateFormatter(FastDateFormat fastDateFormat) {
	this.fastDateFormat = fastDateFormat;
	onSecond = fastDateFormat.getPattern().indexOf("SSS") == -1;

	long current = System.currentTimeMillis();
	this.cachedTime = new AtomicReference<CachedTime>(new CachedTime(current, fastDateFormat.format(current)));
}
 
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: DateUtil.java    From KlyphMessenger with MIT License 5 votes vote down vote up
public static String getShortDateTime(String unixDate)
	{
		Date date = new Date(Long.parseLong(unixDate)*1000);
		Calendar c1 = Calendar.getInstance();
		Calendar c2 = Calendar.getInstance();
		c2.setTime(date);
		
		
		FastDateFormat dateFormat = FastDateFormat.getDateTimeInstance(FastDateFormat.MEDIUM, FastDateFormat.SHORT);
		String pattern = dateFormat.getPattern();
		
		// If not same year
		if (c1.get(Calendar.YEAR) == c2.get(Calendar.YEAR))
		{
			pattern = pattern.replace("y", "");
			
			if (pattern.indexOf("/") == 0 || pattern.indexOf("-") == 0 || pattern.indexOf(".") == 0  || pattern.indexOf("年") == 0)
			{
				pattern = pattern.substring(1);
			}
			
/*			pattern = pattern.replace("EEEE", "EEE");
			pattern = pattern.replace("MMMM", "");
			pattern = pattern.replace("d", "");
		}
		else
		{
			pattern = pattern.replace("MMMM", "MMM");
			pattern = pattern.replace("EEEE", "");*/
		}
		
		pattern = pattern.replace("  ", " ");
		pattern = pattern.trim();
		
		dateFormat = FastDateFormat.getInstance(pattern);
		
		return dateFormat.format(date);
	}
 
Example #14
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 #15
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 #16
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 #17
Source File: DateAdapter.java    From recheck with GNU Affero General Public License v3.0 5 votes vote down vote up
@Override
public Date unmarshal( final String value ) {
	if ( value == null ) {
		return null;
	}
	for ( final FastDateFormat dateFormat : possibleDateFormats ) {
		try {
			return dateFormat.parse( value );
		} catch ( final ParseException ignored ) {/* NOP */}
	}
	throw new RuntimeException( "Can't parse date '" + value + "'!" );
}
 
Example #18
Source File: DateUtil.java    From KlyphMessenger with MIT License 5 votes vote down vote up
private static FastDateFormat getDateFormat()
{
	FastDateFormat dateFormat = FastDateFormat.getDateInstance(FastDateFormat.FULL);
	String pattern = dateFormat.getPattern();

	pattern = pattern.replace("y", "");
	pattern = pattern.replace("E", "");
	pattern = pattern.replace(",", "");
	pattern = pattern.replace("  ", " ");
	pattern = pattern.trim();

	return FastDateFormat.getInstance(pattern);
}
 
Example #19
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 #20
Source File: CachingDateFormatter.java    From j360-dubbo-app-all with Apache License 2.0 5 votes vote down vote up
public CachingDateFormatter(FastDateFormat fastDateFormat) {
	this.fastDateFormat = fastDateFormat;
	onSecond = fastDateFormat.getPattern().indexOf("SSS") == -1;

	long current = System.currentTimeMillis();
	this.cachedTime = new AtomicReference<CachedTime>(new CachedTime(current, fastDateFormat.format(current)));
}
 
Example #21
Source File: StandardJsonLogger.java    From slf4j-json-logger with Apache License 2.0 5 votes vote down vote up
public StandardJsonLogger(org.slf4j.Logger slf4jLogger,
                          FastDateFormat formatter, Gson gson,
                          String levelName,
                          Consumer<String> logOperation,
                          BiConsumer<Marker, String> logWithMarkerOperation) {
  this.slf4jLogger = slf4jLogger;
  this.formatter = formatter;
  this.gson = gson;

  this.levelName = levelName;
  this.logOperation = logOperation;
  this.logWithMarkerOperation = logWithMarkerOperation;

  this.jsonObject = new JsonObject();
}
 
Example #22
Source File: DateUtil.java    From alibaba-flink-connectors with Apache License 2.0 5 votes vote down vote up
private static FastDateFormat getDateFormat(String timeZone, String format){
	String key = String.valueOf(timeZone) + String.valueOf(format);
	if (null == timeZone || timeZone.isEmpty()){
		return dfTimeStamp;
	}
	if (sdfCache.containsKey(key)){
		return sdfCache.get(key);
	} else {
		FastDateFormat sdf = FastDateFormat.getInstance(format, TimeZone.getTimeZone(timeZone));
		sdfCache.put(key, sdf);
		return sdf;
	}
}
 
Example #23
Source File: JwtServiceImpl.java    From paas with Apache License 2.0 5 votes vote down vote up
@Override
public ResultVO listToken() {
    FastDateFormat format = FastDateFormat.getInstance("yyyy-MM-dd HH:mm:ss");
    Map<String, Map<String, String>> map = new HashMap<>(16);
    try {
        // 取出所有用户
        Set<String> fields = jedisClient.hkeys(key);

        for(String uid : fields) {
            String token = jedisClient.hget(key, uid);
            Map<String, String> tokenMap = new HashMap<>(16);
            tokenMap.put("token", token);

            ResultVO resultVO = checkToken(token);
            if(resultVO.getCode() == ResultEnum.OK.getCode()) {
                Map data = (Map) resultVO.getData();

                long timestamp = (long) data.get("timestamp");
                tokenMap.put("createDate", format.format(timestamp));
            } else {
                tokenMap.put("createDate", "已过期");
            }

            map.put(uid, tokenMap);
        }

        return ResultVOUtils.success(map);
    } catch (Exception e) {
        log.error("token缓存出现错误,错误位置:{},错误栈:{}", "JwtServiceImpl.listToken()", HttpClientUtils.getStackTraceAsString(e));
        return ResultVOUtils.error(ResultEnum.TOKEN_READ_ERROR);
    }
}
 
Example #24
Source File: Lang3UtilsUnitTest.java    From tutorials with MIT License 5 votes vote down vote up
@Test
public void test_getInstance_String_Locale() {
    final FastDateFormat format1 = FastDateFormat.getInstance("MM/DD/yyyy", Locale.US);
    final FastDateFormat format3 = FastDateFormat.getInstance("MM/DD/yyyy", Locale.GERMANY);

    assertNotSame(format1, format3);
}
 
Example #25
Source File: StackTest.java    From slf4j-json-logger with Apache License 2.0 5 votes vote down vote up
@Before
public void before() {
  this.slf4jLogger = Mockito.mock(org.slf4j.Logger.class);
  this.gson = new GsonBuilder().disableHtmlEscaping().create();
  this.formatter = FastDateFormat.getInstance(dateFormatString);

  logger = new StandardJsonLogger(slf4jLogger, formatter, gson, null, null, null) {
    @Override
    public void log() {
      logMessage = formatMessage("INFO");
    }
  };
}
 
Example #26
Source File: FilmlisteLesen.java    From MLib with GNU General Public License v3.0 5 votes vote down vote up
private void notifyFertig(String url, ListeFilme liste) {
    Log.sysLog("Liste Filme gelesen am: " + FastDateFormat.getInstance("dd.MM.yyyy, HH:mm").format(new Date()));
    Log.sysLog("  erstellt am: " + liste.genDate());
    Log.sysLog("  Anzahl Filme: " + liste.size());
    for (ListenerFilmeLaden l : listeners.getListeners(ListenerFilmeLaden.class)) {
        l.fertig(new ListenerFilmeLadenEvent(url, "", max, progress, 0, false));
    }
}
 
Example #27
Source File: DateTimeUtils.java    From jackdaw with Apache License 2.0 5 votes vote down vote up
public static Collection<Format> createDateFormats(final String... formats) {
    final ImmutableList.Builder<Format> builder = ImmutableList.builder();
    for (final String format : formats) {
        final FastDateFormat instance = FastDateFormat.getInstance(format);
        builder.add(instance);
    }
    return builder.build();
}
 
Example #28
Source File: DateParamConverter.java    From openmeetings with Apache License 2.0 5 votes vote down vote up
public static Date get(String val) {
	if (Strings.isEmpty(val)) {
		return null;
	}
	for (FastDateFormat df : formats) {
		try {
			return df.parse(val);
		} catch (ParseException e) {
			// no-op
		}
	}
	throw new IllegalArgumentException("Unparsable format: " + val);
}
 
Example #29
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 #30
Source File: DateUtil.java    From Klyph with MIT License 5 votes vote down vote up
public static String getShortDateTime(String unixDate)
	{
		Date date = new Date(Long.parseLong(unixDate)*1000);
		Calendar c1 = CALENDAR;
		c1.setTime(new Date());
		Calendar c2 = Calendar.getInstance();
		c2.setTime(date);
		
		
		FastDateFormat dateFormat = FastDateFormat.getDateTimeInstance(FastDateFormat.MEDIUM, FastDateFormat.SHORT);
		String pattern = dateFormat.getPattern();
		
		// If not same year
		if (c1.get(Calendar.YEAR) == c2.get(Calendar.YEAR))
		{
			pattern = pattern.replace("y", "");
			
			if (pattern.indexOf("/") == 0 || pattern.indexOf("-") == 0 || pattern.indexOf(".") == 0  || pattern.indexOf("年") == 0)
			{
				pattern = pattern.substring(1);
			}
			
/*			pattern = pattern.replace("EEEE", "EEE");
			pattern = pattern.replace("MMMM", "");
			pattern = pattern.replace("d", "");
		}
		else
		{
			pattern = pattern.replace("MMMM", "MMM");
			pattern = pattern.replace("EEEE", "");*/
		}
		
		pattern = pattern.replace("  ", " ");
		pattern = pattern.trim();
		
		dateFormat = FastDateFormat.getInstance(pattern);
		
		return dateFormat.format(date);
	}