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

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

源代码1 项目: spork   文件: CustomFormatToISO.java
@Override
public String exec(Tuple input) throws IOException
{
    if (input == null || input.size() < 2) {
        return null;
    }

    if (input.get(0) == null || input.get(1) == null) {
        return null;
    }

    String date = input.get(0).toString();
    String format = input.get(1).toString();

    // See http://joda-time.sourceforge.net/api-release/org/joda/time/format/DateTimeFormat.html
    DateTimeFormatter parser = DateTimeFormat.forPattern(format);
    DateTime result;
    try {
        result = parser.withOffsetParsed().parseDateTime(date);
    } catch(Exception e) {
        return null;
    }

    return result.toString();
}
 
源代码2 项目: presto   文件: CustomDateTimeJsonFieldDecoder.java
public CustomDateTimeJsonFieldDecoder(DecoderColumnHandle columnHandle)
{
    this.columnHandle = requireNonNull(columnHandle, "columnHandle is null");
    if (!SUPPORTED_TYPES.contains(columnHandle.getType())) {
        throwUnsupportedColumnType(columnHandle);
    }

    checkArgument(columnHandle.getFormatHint() != null, "format hint not defined for column '%s'", columnHandle.getName());
    try {
        formatter = DateTimeFormat.forPattern(columnHandle.getFormatHint()).withLocale(Locale.ENGLISH).withZoneUTC();
    }
    catch (IllegalArgumentException e) {
        throw new PrestoException(
                GENERIC_USER_ERROR,
                format("invalid joda pattern '%s' passed as format hint for column '%s'", columnHandle.getFormatHint(), columnHandle.getName()));
    }
}
 
源代码3 项目: incubator-gobblin   文件: DayPartitioner.java
public DayPartitioner(State state, int numBranches, int branchId) {
  _withColumnNames = state.getPropAsBoolean(GoggleIngestionConfigurationKeys.KEY_INCLUDE_COLUMN_NAMES, false);
  _prefix = state.getProp(GoggleIngestionConfigurationKeys.KEY_PARTITIONER_PREFIX);
  _withPrefix = StringUtils.isNotBlank(_prefix);

  _dateColumn = state.getProp(GoggleIngestionConfigurationKeys.KEY_DATE_COLUMN_NAME, DEFAULT_DATE_COLUMN);
  _dateFormatter =
      DateTimeFormat.forPattern(state.getProp(GoggleIngestionConfigurationKeys.KEY_DATE_FORMAT, DEFAULT_DATE_FORMAT));

  SchemaBuilder.FieldAssembler<Schema> assembler = SchemaBuilder.record(NAME).namespace(NAME_SPACE).fields();
  Schema stringType = Schema.create(Schema.Type.STRING);

  if (_withPrefix) {
    assembler = assembler.name(PARTITION_COLUMN_PREFIX).type(stringType).noDefault();
  }
  _partitionSchema =
      assembler.name(PARTITION_COLUMN_YEAR).type(stringType).noDefault().name(PARTITION_COLUMN_MONTH).type(stringType)
          .noDefault().name(PARTITION_COLUMN_DAY).type(stringType).noDefault().endRecord();
}
 
源代码4 项目: flowable-engine   文件: CustomConfigRuntimeTest.java
@Test
@DmnDeployment(resources = "org/flowable/dmn/engine/test/deployment/post_custom_expression_function_expression_1.dmn")
public void customExpressionFunctionMissingDefaultFunction() {

    DmnEngine dmnEngine = flowableRule2.getDmnEngine();
    DmnDecisionService ruleService = dmnEngine.getDmnDecisionService();

    DateTimeFormatter dateTimeFormatter = DateTimeFormat.forPattern("yyyy-MM-dd");
    LocalDate localDate = dateTimeFormatter.parseLocalDate("2015-09-18");

    DecisionExecutionAuditContainer result = ruleService.createExecuteDecisionBuilder()
            .decisionKey("decision")
            .variable("input1", localDate.toDate())
            .executeWithAuditTrail();

    assertThat(result.getDecisionResult()).isEmpty();
    assertThat(result.isFailed()).isTrue();
}
 
@NotNull private static List<String> handleUrlWithDateFormat(String url) {
    List<String> urls = new ArrayList<>();
    Pattern dateFormatPattern = Pattern.compile("\\{date\\(([^)]+)\\)\\}");
    Matcher matcher = dateFormatPattern.matcher(url);
    if (matcher.find()) {
        String pattern = matcher.group(1);
        for (int j = 0; j < 7; j++) {
            LocalDate date = LocalDate.now().plusDays(j);
            String dateStr = DateTimeFormat.forPattern(pattern).print(date);
            String urlWithDate = matcher.replaceFirst(dateStr);
            urls.add(urlWithDate);
        }
    } else {
        urls.add(url);
    }
    return urls;
}
 
源代码6 项目: Raigad   文件: TestIndexNameFilter.java
@Test
public void testHourlyIndexNameFilter() {
    DateTimeFormatter formatter = DateTimeFormat.forPattern("'abcd'YYYYMMddHH");
    IIndexNameFilter filter = new DatePatternIndexNameFilter(formatter);

    assertTrue(filter.filter("abcd2013120300"));

    assertTrue(filter.filter("abcd2013120301"));

    assertTrue(filter.filter("abcd2013120312"));

    assertTrue(filter.filter("abcd2013120323"));

    assertFalse(filter.filter("abcd12013120323"));

    assertFalse(filter.filter("abcd2013120324"));
    assertFalse(filter.filter("abcd2013120345"));
    assertFalse(filter.filter("abcd20231248"));
    assertFalse(filter.filter("_abc"));
}
 
源代码7 项目: MaxKey   文件: InMemoryOptTokenStore.java
@Override
public boolean validate(UserInfo userInfo, String token, String type, int interval) {
    OneTimePassword otp = optTokenStore.get(userInfo.getUsername() + "_" + type + "_" + token);
    if (otp != null) {
        DateTime currentdateTime = new DateTime();
        DateTime oneCreateTime = DateTime.parse(otp.getCreateTime(),
                DateTimeFormat.forPattern("yyyy-MM-dd HH:mm:ss"));
        Duration duration = new Duration(oneCreateTime, currentdateTime);
        int intDuration = Integer.parseInt(duration.getStandardSeconds() + "");
        logger.debug("validate duration " + intDuration);
        logger.debug("validate result " + (intDuration <= interval));
        if (intDuration <= interval) {
            return true;
        }
    }
    return false;
}
 
源代码8 项目: program-ab   文件: Interval.java
public static int getMonthsBetween(final String date1, final String date2, String format){
    try {
    final DateTimeFormatter fmt =
            DateTimeFormat
                    .forPattern(format)
                    .withChronology(
                            LenientChronology.getInstance(
                                    GregorianChronology.getInstance()));
    return Months.monthsBetween(
            fmt.parseDateTime(date1),
            fmt.parseDateTime(date2)
    ).getMonths();
    } catch (Exception ex) {
        ex.printStackTrace();
        return 0;
    }
}
 
源代码9 项目: h2o-2   文件: Inspect2.java
public static String x1( Vec v, long row, double d ) {
  if( (row >= 0 && v.isNA(row)) || Double.isNaN(d) )
    return "-";               // Display of missing elements
  if( v.isEnum() ) return row >= 0 ? v.domain(v.at8(row)) : Long.toString((long)d);
  if( v.isTime() ) {
    String tpat = v.timeParse();
    DateTime dt = new DateTime(row >= 0 ? v.at8(row) : (long)d);
    DateTimeFormatter fmt = DateTimeFormat.forPattern(tpat);
    String str = fmt.print(dt);
    return str;
  }
  if( v.isInt() )  return Long.toString(row >= 0 ? v.at8(row) : (long)d);
  Chunk c = v.chunkForChunkIdx(0);
  Class Cc = c.getClass();
  if( Cc == C1SChunk.class ) return x2(d,((C1SChunk)c)._scale);
  if( Cc == C2SChunk.class ) return x2(d,((C2SChunk)c)._scale);
  return Double.toString(d);
}
 
源代码10 项目: OpenLRW   文件: RiskService.java
/**
 * Add a criteria to get the Risks for the given day
 *
 * @param query
 * @param date yyyy-MM-dd or latest
 */
private void dayCriteria(Query query, String date){
    DateTimeFormatter formatter = DateTimeFormat.forPattern("yyyy-MM-dd");
    if (!date.isEmpty()) {
        if (date.equals("latest")){
            query.limit(1);
        } else {
            try {
                DateTime startDate = formatter.parseDateTime(date).withZone(DateTimeZone.UTC);
                DateTime endDate = startDate.plusDays(1);
                query.addCriteria(where("dateTime").gte(startDate).lt(endDate)); // Get the risks for the day given
            } catch (Exception e) {
                throw new BadRequestException("Not able to parse the date, it has to be in the following format: `yyyy-MM-dd` ");
            }
        }
    }
}
 
源代码11 项目: ipst   文件: LocalOnlineApplication.java
@Override
public String startProcess(String name, String owner, DateTime date, DateTime creationDate,
        OnlineWorkflowStartParameters start, OnlineWorkflowParameters params, DateTime[] basecases, int numThreads)
                throws Exception {
    Objects.requireNonNull(date);
    Objects.requireNonNull(creationDate);
    Objects.requireNonNull(params);
    Objects.requireNonNull(basecases);
    config = OnlineConfig.load();
    OnlineDb onlineDb = config.getOnlineDbFactoryClass().newInstance().create();
    String processId = DateTimeFormat.forPattern("yyyyMMddHHmmSSS").print(new DateTime());
    LOGGER.info("Starting process: " + processId);
    OnlineProcess proc = new OnlineProcess(processId, name, owner, params.getCaseType().toString(), date, creationDate);

    ExecutorService taskExecutor = Executors.newFixedThreadPool(numThreads);
    List<Callable<Void>> tasks = new ArrayList<>(numThreads);

    for (DateTime basecase : basecases) {
        tasks.add(new Callable() {
            @Override
            public Object call() throws Exception {
                OnlineWorkflowParameters pars = new OnlineWorkflowParameters(basecase, params.getStates(), params.getHistoInterval(), params.getOfflineWorkflowId(), params.getTimeHorizon(), params.getFeAnalysisId(), params.getRulesPurityThreshold(), params.storeStates(), params.analyseBasecase(), params.validation(), params.getSecurityIndexes(), params.getCaseType(), params.getCountries(), params.isMergeOptimized(), params.getLimitReduction(), params.isHandleViolationsInN(), params.getConstraintMargin());
                String workflowId = startWorkflow(start, pars);
                org.joda.time.format.DateTimeFormatter fmt = ISODateTimeFormat.dateTime();
                String basecaseString = fmt.print(basecase);
                proc.addWorkflow(basecaseString, workflowId);
                return workflowId;
            } });

    }
    taskExecutor.invokeAll(tasks);
    taskExecutor.shutdown();

    onlineDb.storeProcess(proc);
    LOGGER.info("End of process: " + processId);
    return processId;
}
 
源代码12 项目: DataVec   文件: DeriveColumnsFromTimeTransform.java
public DerivedColumn(@JsonProperty("columnName") String columnName,
                @JsonProperty("columnType") ColumnType columnType, @JsonProperty("format") String format,
                @JsonProperty("dateTimeZone") DateTimeZone dateTimeZone,
                @JsonProperty("fieldType") DateTimeFieldType fieldType) {
    this.columnName = columnName;
    this.columnType = columnType;
    this.format = format;
    this.dateTimeZone = dateTimeZone;
    this.fieldType = fieldType;
    if (format != null)
        dateTimeFormatter = DateTimeFormat.forPattern(this.format).withZone(dateTimeZone);
}
 
源代码13 项目: incubator-gobblin   文件: Utils.java
/**
 * Convert timestamp in a string format to joda time
 * @param input timestamp
 * @param format timestamp format
 * @param timezone time zone of timestamp
 * @return joda time
 */
public static DateTime toDateTime(String input, String format, String timezone) {
  String tz = StringUtils.defaultString(timezone, ConfigurationKeys.DEFAULT_SOURCE_TIMEZONE);
  DateTimeZone dateTimeZone = getTimeZone(tz);
  DateTimeFormatter inputDtFormat = DateTimeFormat.forPattern(format).withZone(dateTimeZone);
  DateTime outputDateTime = inputDtFormat.parseDateTime(input).withZone(dateTimeZone);
  return outputDateTime;
}
 
源代码14 项目: Qualitis   文件: IndexServiceImpl.java
private List<IndexApplicationChartResponse> getApplicationChartPerDayRange(String startDate, String endDate, List<Application> applications) {
  DateTimeFormatter formatter = DateTimeFormat.forPattern(DATE_FORMAT_PATTERN);
  Date calendarEndDate = DateTime.parse(endDate, formatter).toDate();
  Date calendarStartDate = DateTime.parse(startDate, formatter).toDate();

  int stepSize = DateUtils.getDayDiffBetween(calendarStartDate, calendarEndDate);
  return getApplicationChartPerDayRecent(calendarEndDate, -(stepSize + 1), applications);
}
 
源代码15 项目: streams   文件: StreamsDateTimeDeserializer.java
protected StreamsDateTimeDeserializer(Class<DateTime> dateTimeClass, List<String> formats) {
  super(dateTimeClass);
  for ( String format : formats ) {
    try {
      formatters.add(DateTimeFormat.forPattern(format));
    } catch (Exception ex) {
      LOGGER.warn("Exception parsing format " + format);
    }
  }
}
 
源代码16 项目: website   文件: ProductFieldSetMapper.java
private LocalDateTime getDateTime(String dateString) {
	if (!StringUtils.isBlank(dateString)) {
		String pattern;
		if (dateString.matches("(19|20)[0-9]{2}[/](0[1-9]|1[012])[/](0[1-9]|[12][0-9]|3[01])")) {
			pattern = "yyyy/MM/dd";
		} else {
			pattern = "yyyy-MM-dd";
		}
		DateTimeFormatter dateTimeFormatter = DateTimeFormat.forPattern(pattern);
		return dateTimeFormatter.parseLocalDateTime(dateString);
	}
	return null;
}
 
源代码17 项目: actframework   文件: Policy.java
public DateTime effectiveDate() {
    if (null == effectiveDate) {
        return null;
    }
    DateTimeFormatter fmt = DateTimeFormat.forPattern("yyyy-MM-dd'T'HH:mm:ss.SSS");
    return fmt.parseDateTime(effectiveDate);
}
 
源代码18 项目: SimpleFlatMapper   文件: JodaTimeHelperTest.java
@Test
public void testFormattersFromFormatterWithSpecifiedTZ() {
    final DateTimeFormatter yyyyMMdd = JodaTimeHelper.getDateTimeFormatters(DATE_TIME_FORMATTER_SUPPLIER_TZ, TIME_ZONE_SUPPLIER)[0];
    final long instant = System.currentTimeMillis();
    assertEquals(DateTimeFormat.forPattern("ddMMyyyy").withZone(NY_TZ).print(instant), yyyyMMdd.print(instant));
    assertEquals(NY_TZ, yyyyMMdd.getZone());
}
 
源代码19 项目: incubator-gobblin   文件: Extract.java
/**
 * Constructor.
 *
 * @param state a {@link SourceState} carrying properties needed to construct an {@link Extract}
 * @param namespace dot separated namespace path
 * @param type {@link TableType}
 * @param table table name
 *
 * @deprecated Extract does not use any property in {@link SourceState}.
 * Use {@link #Extract(TableType, String, String)}
 */
@Deprecated
public Extract(SourceState state, TableType type, String namespace, String table) {
  // Values should only be null for deserialization
  if (state != null && type != null && !Strings.isNullOrEmpty(namespace) && !Strings.isNullOrEmpty(table)) {
    // Constructing DTF
    DateTimeZone timeZone = getTimeZoneHelper(state);

    DateTimeFormatter DTF = DateTimeFormat.forPattern("yyyyMMddHHmmss").withLocale(Locale.US).withZone(timeZone);

    String extractId = DTF.print(new DateTime());
    super.addAll(state);
    super.setProp(ConfigurationKeys.EXTRACT_TABLE_TYPE_KEY, type.toString());
    super.setProp(ConfigurationKeys.EXTRACT_NAMESPACE_NAME_KEY, namespace);
    super.setProp(ConfigurationKeys.EXTRACT_TABLE_NAME_KEY, table);
    super.setProp(ConfigurationKeys.EXTRACT_EXTRACT_ID_KEY, extractId);

    for (WorkUnitState pre : state.getPreviousWorkUnitStates()) {
      Extract previousExtract = pre.getWorkunit().getExtract();
      if (previousExtract.getNamespace().equals(namespace) && previousExtract.getTable().equals(table)) {
        this.previousTableState.addAll(pre);
      }
    }

    // Setting full drop date if not already specified, the value can still be overridden if required.
    if (state.getPropAsBoolean(ConfigurationKeys.EXTRACT_IS_FULL_KEY)
        && !state.contains(ConfigurationKeys.EXTRACT_FULL_RUN_TIME_KEY)) {
      super.setProp(ConfigurationKeys.EXTRACT_FULL_RUN_TIME_KEY, System.currentTimeMillis());
    }
  }
}
 
源代码20 项目: astor   文件: LocalDateTime.java
/**
 * Output the date using the specified format pattern.
 *
 * @param pattern  the pattern specification, null means use <code>toString</code>
 * @see org.joda.time.format.DateTimeFormat
 */
public String toString(String pattern) {
    if (pattern == null) {
        return toString();
    }
    return DateTimeFormat.forPattern(pattern).print(this);
}
 
源代码21 项目: astor   文件: YearMonth.java
/**
 * Output the year-month using the specified format pattern.
 *
 * @param pattern  the pattern specification, null means use <code>toString</code>
 * @see org.joda.time.format.DateTimeFormat
 */
public String toString(String pattern) {
    if (pattern == null) {
        return toString();
    }
    return DateTimeFormat.forPattern(pattern).print(this);
}
 
源代码22 项目: flowable-engine   文件: RuntimeTest.java
@Test
@DmnDeployment(resources = "org/flowable/dmn/engine/test/deployment/dates_5.dmn")
public void localDatesEquals() {
    DateTimeFormatter dateTimeFormatter = DateTimeFormat.forPattern("yyyy-MM-dd");
    LocalDate localDate = dateTimeFormatter.parseLocalDate("2015-09-18");

    Map<String, Object> result = ruleService.createExecuteDecisionBuilder()
            .decisionKey("decision")
            .variable("input1", localDate)
            .executeWithSingleResult();
    assertThat(result.get("output1").getClass()).isSameAs(String.class);
    assertThat(result.get("output1")).isEqualTo("test2");
}
 
源代码23 项目: activiti6-boot2   文件: RuntimeTest.java
@Test
@DmnDeploymentAnnotation(resources = "org/activiti/dmn/engine/test/deployment/reservered_word.dmn")
public void executeDecision_reserved_word() {
  Map<String, Object> processVariablesInput = new HashMap<String, Object>();

    DateTimeFormatter dateTimeFormatter = DateTimeFormat.forPattern("yyyy-MM-dd");
    LocalDate localDate = dateTimeFormatter.parseLocalDate("2015-09-18");

    processVariablesInput.put("date", 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");
}
 
源代码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 项目: SI   文件: ContentInstanceAnncDAO.java
public Resource retrieveLatest(String parentUri, RESULT_CONT resultContent) throws OneM2MException {		
	
	String now = LocalDateTime.now().toString(DateTimeFormat.forPattern("yyyyMMdd'T'HHmmss"));

	DBObject c1 = new BasicDBObject(EXPIRETIME_KEY, null);
	DBObject c2 = new BasicDBObject(EXPIRETIME_KEY, new BasicDBObject("$gt", now));
	
	BasicDBList or = new BasicDBList();
	or.add(c1);
	or.add(c2);
	
	BasicDBObject query = new BasicDBObject("$or", or).append(PARENTID_KEY,  parentUri);
	
	List<Document>childList = getDocuments(query, RESOURCE_TYPE.CONTENT_INST, CREATETIME_KEY, false, 1);

	if (childList.size() == 0) {
		return null;
	}

	Document doc = childList.get(0);

	try {
		DaoJSONConvertor<ContentInstanceAnnc> cvt = (DaoJSONConvertor<ContentInstanceAnnc>)ConvertorFactory.getDaoJSONConvertor(ContentInstanceAnnc.class, ContentInstanceAnnc.SCHEMA_LOCATION);
		//DaoJSONConvertor<ContentInstance> cvt = new DaoJSONConvertor<ContentInstance>(ContentInstance.class);
		Resource res = (Resource) cvt.unmarshal(doc.toJson());
		res.setUri(doc.getString(URI_KEY));
		
		return res;
	} catch (Exception e) {
		log.debug("Handled exception", e);
		
		throw new OneM2MException(RESPONSE_STATUS.INTERNAL_SERVER_ERROR, "Exception during initialization of resource using document.(retrieveOldest)");
	}
	
}
 
/**
 * Update the widget helper date text (useful for those who don't know the other calendar)
 */
protected void updateGregorianDateHelperDisplay() {
    DateTime dtLMDGreg = new DateTime(getCurrentMillis());
    DateTimeFormatter fmt = DateTimeFormat.forPattern("d MMMM yyyy");
    String str = fmt.print(dtLMDGreg);
    txtGregorian.setText("(" + str + ")");
}
 
源代码27 项目: heat   文件: DateHandler.java
/**
 * getFormattedDate takes a string input and return the formatted date.
 * @param inputDate is an input a string like ${TODAY} or ${TODAY+1}
 * @return formatted date as String
 */
public String getFormattedDate(String inputDate) {
    String outputDate = "";
    DateTime dateToParse = getDateTime(inputDate);
    String patternForFormat = "\\$\\{" + DateHeatPlaceholderModule.TODAY_PLACEHOLDER_KEYWORD + ".*_(.*?)\\}";
    Pattern formatPattern = Pattern.compile(patternForFormat);
    Matcher formatMatcher = formatPattern.matcher(inputDate);
    String format = DateHeatPlaceholderModule.TODAY_PLACEHOLDER_DEFAULT_PATTERN;
    if (formatMatcher.find()) {
        format = formatMatcher.group(1);
    }
    dtfOut = DateTimeFormat.forPattern(format);
    outputDate = dtfOut.print(dateToParse);
    return outputDate;
}
 
源代码28 项目: atdl4j   文件: DateTimeConverter.java
@Override
public String convertParameterValueToFixWireValue(Object aParameterValue)
{
	DateTime date = convertParameterValueToParameterComparable( aParameterValue ); 
	
	if ( date != null )
	{
		DateTimeFormatter fmt = DateTimeFormat.forPattern( getFormatString() );
		return fmt.withZone( DateTimeZone.UTC ).print( date );
	}
	else
	{
		return null;
	}
}
 
Date expiresOn() {
    if (expiresOnDate == null) {
        try {
            expiresOnDate = DateTime.parse(expiresOn, DateTimeFormat.forPattern("yyyy-MM-dd HH:mm:ss.SSSSSS")).toDate();
        } catch (IllegalArgumentException e) {
            expiresOnDate = DateTime.parse(expiresOn).toDate();
        }
    }
    return expiresOnDate;
}
 
源代码30 项目: quartz-glass   文件: DayOfWeekDescriptionBuilder.java
@Override
protected String getSingleItemDescription(String expression) {
    String exp = expression;
    if (expression.contains("#")) {
        exp = expression.substring(0, expression.indexOf("#"));
    } else if (expression.contains("L")) {
        exp = exp.replace("L", "");
    }
    if (StringUtils.isNumeric(exp)) {
        return DateAndTimeUtils.getDayOfWeekName(Integer.parseInt(exp));
    } else {
        return DateTimeFormat.forPattern("EEE").withLocale(Locale.ENGLISH)
                .parseDateTime(WordUtils.capitalizeFully(exp)).dayOfWeek().getAsText(Locale.ENGLISH);
    }
}
 
 类所在包
 同包方法