下面列出了怎么用org.apache.commons.lang3.time.FastDateFormat的API类实例代码及写法,或者点击链接到github查看源代码。
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);
}
}
}
/**
* 获取某月有几天
* @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;
}
/**
* 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;
}
@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;
}
/**
* 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));
}
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;
}
/**
* 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));
}
/**
* 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));
}
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);
}
}
@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");
}
};
}
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;
}
}
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);
}
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;
}
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);
}
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);
}
@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 + "'!" );
}
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);
}
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)));
}
@Test
public void test3() throws Exception {
FastDateFormat formatter = org.apache.kylin.common.util.DateFormat.getDateFormat("MM dd, yyyy hh:mm:ss a");
String timeStr = "07 20, 2016 09:59:17 AM";
System.out.println(formatter.parse(timeStr).getTime());
}
/**
* 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);
}
}
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);
}
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)));
}
/**
* 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);
}
}
@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);
}
}
@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);
}
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));
}
}
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();
}
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);
}
/**
* 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 );
}
}
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();
}