下面列出了怎么用org.joda.time.format.DateTimeFormatter的API类实例代码及写法,或者点击链接到github查看源代码。
/**
* 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);
}
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;
}
}
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);
}
@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");
}
/**
* 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);
}
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;
}
@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;
}
}
/**
* 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];
}
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();
}
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);
}
public void testTimeSeriesReader() throws Exception {
DateTimeFormatter formatter = HMConstants.utcDateFormatterYYYYMMDDHHMM;
URL dataUrl = this.getClass().getClassLoader().getResource("timeseriesreader_test.csv");
String dataPath = new File(dataUrl.toURI()).getAbsolutePath();
OmsTimeSeriesReader reader = new OmsTimeSeriesReader();
reader.file = dataPath;
reader.read();
HashMap<DateTime, double[]> outData = reader.outData;
Set<Entry<DateTime, double[]>> entrySet = outData.entrySet();
Iterator<Entry<DateTime, double[]>> iterator = entrySet.iterator();
Entry<DateTime, double[]> next = iterator.next();
assertEquals(10.0, next.getValue()[0]);
assertEquals("2000-01-01 00:00", next.getKey().toString(formatter));
next = iterator.next();
next = iterator.next();
assertEquals(1.0, next.getValue()[0]);
assertEquals("2000-01-01 02:00", next.getKey().toString(formatter));
next = iterator.next();
next = iterator.next();
assertEquals(2.0, next.getValue()[0]);
assertEquals("2000-01-01 04:00", next.getKey().toString(formatter));
reader.close();
}
@ScalarFunction("from_iso8601_timestamp")
@LiteralParameters("x")
@SqlType("timestamp(3) with time zone")
public static long fromISO8601Timestamp(ConnectorSession session, @SqlType("varchar(x)") Slice iso8601DateTime)
{
DateTimeFormatter formatter = ISODateTimeFormat.dateTimeParser()
.withChronology(getChronology(session.getTimeZoneKey()))
.withOffsetParsed();
return packDateTimeWithZone(parseDateTimeHelper(formatter, iso8601DateTime.toStringUtf8()));
}
@Test
public void testWriteReportToLocal() throws IOException {
//given
String rootPath = folder.getRoot().getPath();
DateTimeFormatter DT_FMT = DateTimeFormat.forPattern("yyyyMMddHH").withZoneUTC();
CallableQuery callableQuery = new CallableQuery();
PersistentResultSet result = new PersistentResultSet();
result.setColumnNames(Arrays.asList("entry_id", "title", "social"));
result.setColumnTypes(Arrays.asList("String", "String", "int"));
result.setData(Arrays.asList(Arrays.asList((Object)"1", "Video", 90),
Arrays.asList((Object)"2", "TV Shows", 500),
Arrays.asList((Object)"3", "Facts", 1)));
JobSpec jobSpec = getTestJob("ajob", new JobDaoImpl());
DateTime dateTime = new DateTime();
PlannedJob plannedJob = new PlannedJob(jobSpec, dateTime);
String jobId = String.valueOf(jobSpec.getId());
//when
callableQuery.writeReportToLocal(result, rootPath, plannedJob);
//expect
FileReader resultReader = new FileReader(new File(rootPath + "/" + jobId + "/" + DT_FMT.print(dateTime)) + ".tsv");
BufferedReader br = new BufferedReader(resultReader);
Assert.assertEquals("entry_id\ttitle\tsocial\t", br.readLine());
Assert.assertEquals("1\tVideo\t90\t",
br.readLine());
Assert.assertEquals("2\tTV Shows\t500\t",
br.readLine());
Assert.assertEquals("3\tFacts\t1\t",
br.readLine());
br.close();
resultReader.close();
}
public static String getIsoDate(String aDate, String inputPattern, String language)
{
DateTime date = getDateFromString(aDate, inputPattern, language);
DateTimeFormatter outputFormatter = getDateTimeFormatter(ISO_PATTERN, language);
return outputFormatter.print(date);
}
private long convertToTimestamp(String item) {
if (format.isEmpty()) {
return Long.decode(item);
} else {
DateTimeFormatter formatter = DateTimeFormat.forPattern(format);
DateTime parsed = formatter.withZone(getTimeZone()).parseDateTime(item);
return parsed.getMillis();
}
}
@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());
}
private static java.util.Date convertStringToDate(String isoDate) {
isoDate = isoDate.replaceAll("\"", "");
DateTimeFormatter parser = ISODateTimeFormat.dateTimeParser();
DateTime date = parser.parseDateTime(isoDate);
return date.toDate();
}
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;
}
/**
* 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;
}
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);
}
/**
* 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;
}
/**
* 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;
}
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();
}
}
@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 "";
}
@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"));
}
/**
* @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);
}
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);
}
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);
}
@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));
}
/**
* 判断时间是否有效
*
* @param value
* @param formatter
* @return
*/
public static Boolean isValidDate(String value, DateTimeFormatter formatter) {
try {
formatter.parseDateTime(value);
return true;
} catch (Exception e) {
return false;
}
}