Java Code Examples for org.joda.time.format.DateTimeFormat

The following examples show how to use org.joda.time.format.DateTimeFormat. These examples are extracted from open source projects. 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 Project: spork   Source File: CustomFormatToISO.java    License: Apache License 2.0 6 votes vote down vote up
@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();
}
 
Example 2
Source Project: presto   Source File: CustomDateTimeJsonFieldDecoder.java    License: Apache License 2.0 6 votes vote down vote up
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()));
    }
}
 
Example 3
Source Project: incubator-gobblin   Source File: DayPartitioner.java    License: Apache License 2.0 6 votes vote down vote up
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();
}
 
Example 4
Source Project: flowable-engine   Source File: CustomConfigRuntimeTest.java    License: Apache License 2.0 6 votes vote down vote up
@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();
}
 
Example 5
@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;
}
 
Example 6
Source Project: Raigad   Source File: TestIndexNameFilter.java    License: Apache License 2.0 6 votes vote down vote up
@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"));
}
 
Example 7
Source Project: MaxKey   Source File: InMemoryOptTokenStore.java    License: Apache License 2.0 6 votes vote down vote up
@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;
}
 
Example 8
Source Project: program-ab   Source File: Interval.java    License: GNU Lesser General Public License v3.0 6 votes vote down vote up
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;
    }
}
 
Example 9
Source Project: h2o-2   Source File: Inspect2.java    License: Apache License 2.0 6 votes vote down vote up
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);
}
 
Example 10
Source Project: OpenLRW   Source File: RiskService.java    License: Educational Community License v2.0 6 votes vote down vote up
/**
 * 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` ");
            }
        }
    }
}
 
Example 11
Source Project: ipst   Source File: LocalOnlineApplication.java    License: Mozilla Public License 2.0 5 votes vote down vote up
@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;
}
 
Example 12
Source Project: DataVec   Source File: DeriveColumnsFromTimeTransform.java    License: Apache License 2.0 5 votes vote down vote up
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);
}
 
Example 13
Source Project: incubator-gobblin   Source File: Utils.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * 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;
}
 
Example 14
Source Project: Qualitis   Source File: IndexServiceImpl.java    License: Apache License 2.0 5 votes vote down vote up
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);
}
 
Example 15
Source Project: streams   Source File: StreamsDateTimeDeserializer.java    License: Apache License 2.0 5 votes vote down vote up
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);
    }
  }
}
 
Example 16
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;
}
 
Example 17
Source Project: actframework   Source File: Policy.java    License: Apache License 2.0 5 votes vote down vote up
public DateTime effectiveDate() {
    if (null == effectiveDate) {
        return null;
    }
    DateTimeFormatter fmt = DateTimeFormat.forPattern("yyyy-MM-dd'T'HH:mm:ss.SSS");
    return fmt.parseDateTime(effectiveDate);
}
 
Example 18
Source Project: SimpleFlatMapper   Source File: JodaTimeHelperTest.java    License: MIT License 5 votes vote down vote up
@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());
}
 
Example 19
Source Project: incubator-gobblin   Source File: Extract.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * 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());
    }
  }
}
 
Example 20
Source Project: astor   Source File: LocalDateTime.java    License: GNU General Public License v2.0 5 votes vote down vote up
/**
 * 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);
}
 
Example 21
Source Project: astor   Source File: YearMonth.java    License: GNU General Public License v2.0 5 votes vote down vote up
/**
 * 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);
}
 
Example 22
Source Project: flowable-engine   Source File: RuntimeTest.java    License: Apache License 2.0 5 votes vote down vote up
@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");
}
 
Example 23
Source Project: activiti6-boot2   Source File: RuntimeTest.java    License: Apache License 2.0 5 votes vote down vote up
@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");
}
 
Example 24
@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 "";
}
 
Example 25
Source Project: SI   Source File: ContentInstanceAnncDAO.java    License: BSD 2-Clause "Simplified" License 5 votes vote down vote up
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)");
	}
	
}
 
Example 26
/**
 * 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 + ")");
}
 
Example 27
Source Project: heat   Source File: DateHandler.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * 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;
}
 
Example 28
Source Project: atdl4j   Source File: DateTimeConverter.java    License: MIT License 5 votes vote down vote up
@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;
	}
}
 
Example 29
Source Project: autorest-clientruntime-for-java   Source File: AzureCliToken.java    License: MIT License 5 votes vote down vote up
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;
}
 
Example 30
Source Project: quartz-glass   Source File: DayOfWeekDescriptionBuilder.java    License: Apache License 2.0 5 votes vote down vote up
@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);
    }
}