类org.joda.time.format.DateTimeFormatter源码实例Demo

下面列出了怎么用org.joda.time.format.DateTimeFormatter的API类实例代码及写法,或者点击链接到github查看源代码。

源代码1 项目: coming   文件: Elixir_0040_t.java
/**
 * 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);
}
 
源代码2 项目: program-ab   文件: Interval.java
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;
    }
}
 
源代码3 项目: sakai   文件: TimeUtil.java
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);
}
 
源代码4 项目: activiti6-boot2   文件: CustomConfigRuntimeTest.java
@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");
}
 
源代码5 项目: incubator-gobblin   文件: Utils.java
/**
 * 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);
}
 
源代码6 项目: datasync   文件: ControlFileModel.java
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;
  }
}
 
源代码8 项目: astor   文件: Partial.java
/**
 * 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];
}
 
源代码9 项目: product-ei   文件: BPMNUserSubstitutionTestCase.java
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();
}
 
源代码10 项目: sakai   文件: TimeUtil.java
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);
}
 
源代码11 项目: hortonmachine   文件: TestTimeSeriesReader.java
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();
}
 
源代码12 项目: presto   文件: DateTimeFunctions.java
@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()));
}
 
源代码13 项目: chronos   文件: TestCallableQuery.java
@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();
}
 
源代码14 项目: privacy-friendly-shopping-list   文件: DateUtils.java
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);
}
 
源代码15 项目: paperwork   文件: BuildTimeMatcher.java
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();
    }
}
 
源代码16 项目: SimpleFlatMapper   文件: JodaTimeHelperTest.java
@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());

}
 
源代码17 项目: scava   文件: GitLabComment.java
private static java.util.Date convertStringToDate(String isoDate) {
	
	isoDate = isoDate.replaceAll("\"", "");
	DateTimeFormatter parser = ISODateTimeFormat.dateTimeParser();
	DateTime date = parser.parseDateTime(isoDate);
	return date.toDate();
}
 
源代码18 项目: Knowage-Server   文件: SelfServiceDataSetCRUD.java
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;
}
 
源代码19 项目: coming   文件: Nopol2017_0089_t.java
/**
 * 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;
}
 
源代码20 项目: sakai   文件: CalendarUtil.java
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);
}
 
源代码21 项目: coming   文件: Cardumen_00239_s.java
/**
 * 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;
}
 
源代码22 项目: coming   文件: Cardumen_00189_s.java
/**
 * 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();
  }
}
 
源代码24 项目: fenixedu-cms   文件: CMSExtensions.java
@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 "";
}
 
源代码25 项目: amforeas   文件: UtilsTest.java
@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"));
}
 
源代码26 项目: projectforge-webapp   文件: JodaDateConverter.java
/**
 * @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);
}
 
源代码27 项目: sakai   文件: CalendarUtil.java
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);
}
 
源代码29 项目: levelup-java-examples   文件: DatePlusYears.java
@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));
}
 
源代码30 项目: flink-learning   文件: DateUtil.java
/**
 * 判断时间是否有效
 *
 * @param value
 * @param formatter
 * @return
 */
public static Boolean isValidDate(String value, DateTimeFormatter formatter) {
    try {
        formatter.parseDateTime(value);
        return true;
    } catch (Exception e) {
        return false;
    }
}
 
 类所在包
 同包方法