Tabnine Logo
DateTimeFormat
Code IndexAdd Tabnine to your IDE (free)

How to use
DateTimeFormat
in
org.joda.time.format

Best Java code snippets using org.joda.time.format.DateTimeFormat (Showing top 20 results out of 8,046)

Refine searchRefine arrow

  • DateTimeFormatter
  • DateTime
  • DateTimeZone
origin: aws/aws-sdk-java

  /**
   * Returns the current time in yyMMdd-hhmmss format.
   */
  public static String yyMMdd_hhmmss() {
    return DateTimeFormat.forPattern("yyMMdd-hhmmss").print(new DateTime());
  }
}
origin: apache/incubator-gobblin

@Override
public String toString() {
 return "Version " + this.version.toString(DateTimeFormat.shortDateTime()) + " at path " + this.path;
}
origin: joda-time/joda-time

/**
 * Calls upon {@link DateTimeFormat} to parse the pattern and append the
 * results into this builder.
 *
 * @param pattern  pattern specification
 * @throws IllegalArgumentException if the pattern is invalid
 * @see DateTimeFormat
 */
public DateTimeFormatterBuilder appendPattern(String pattern) {
  DateTimeFormat.appendPatternTo(this, pattern);
  return this;
}
origin: spring-projects/spring-framework

private DateTimeFormatter getFallbackFormatter(Type type) {
  switch (type) {
    case DATE: return DateTimeFormat.shortDate();
    case TIME: return DateTimeFormat.shortTime();
    default: return DateTimeFormat.shortDateTime();
  }
}
origin: spring-projects/spring-framework

DateTimeFormatter dateTimeFormatter = null;
if (StringUtils.hasLength(this.pattern)) {
  dateTimeFormatter = DateTimeFormat.forPattern(this.pattern);
  dateTimeFormatter = DateTimeFormat.forStyle(this.style);
  dateTimeFormatter = dateTimeFormatter.withZone(DateTimeZone.forTimeZone(this.timeZone));
origin: fabric8io/docker-maven-plugin

public Builder timeFormatter(String formatOrConstant) {
  if (formatOrConstant == null || formatOrConstant.equalsIgnoreCase("NONE")
    || formatOrConstant.equalsIgnoreCase("FALSE")) {
    timeFormatter = null;
  } else if (formatOrConstant.length() == 0 || formatOrConstant.equalsIgnoreCase("DEFAULT")) {
    timeFormatter = DateTimeFormat.forPattern("HH:mm:ss.SSS");
  } else if (formatOrConstant.equalsIgnoreCase("ISO8601")) {
    timeFormatter = ISODateTimeFormat.dateTime();
  } else if (formatOrConstant.equalsIgnoreCase("SHORT")) {
    timeFormatter = DateTimeFormat.shortDateTime();
  } else if (formatOrConstant.equalsIgnoreCase("MEDIUM")) {
    timeFormatter = DateTimeFormat.mediumDateTime();
  } else if (formatOrConstant.equalsIgnoreCase("LONG")) {
    timeFormatter = DateTimeFormat.longDateTime();
  } else {
    try {
      timeFormatter = DateTimeFormat.forPattern(formatOrConstant);
    } catch (IllegalArgumentException exp) {
      throw new IllegalArgumentException(
          "Cannot parse log date specification '" + formatOrConstant + "'." +
          "Must be either DEFAULT, NONE, ISO8601, SHORT, MEDIUM, LONG or a " +
          "format string parseable by DateTimeFormat. See " +
          "http://joda-time.sourceforge.net/apidocs/org/joda/time/format/DateTimeFormat.html");
    }
  }
  return this;
}
origin: joda-time/joda-time

/**
 * 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);
}
origin: apache/incubator-gobblin

private DateTime getTime (String timeString) {
 DateTimeZone timeZone = DateTimeZone.forID(MRCompactor.DEFAULT_COMPACTION_TIMEZONE);
 int splits = StringUtils.countMatches(timeString, "/");
 String timePattern = "";
 if (splits == 3) {
  timePattern = "YYYY/MM/dd/HH";
 } else if (splits == 2) {
  timePattern = "YYYY/MM/dd";
 }
 DateTimeFormatter timeFormatter = DateTimeFormat.forPattern(timePattern).withZone(timeZone);
 return timeFormatter.parseDateTime (timeString);
}
origin: apache/incubator-druid

DateTimeFormatter event_fmt = DateTimeFormat.forPattern("yyyy-MM-dd'T'HH:mm:ss'Z'");
DateTime dt = new DateTime(zone); // timestamp to put on events
   event_fmt.print(dt), i, 0, i
 );
 LOG.info("sending event: [%s]", event);
 dt = new DateTime(zone);
queryStr = StringUtils.replace(queryStr, "%%DATASOURCE%%", fullDatasourceName);
queryStr = StringUtils.replace(queryStr, "%%TIMEBOUNDARY_RESPONSE_TIMESTAMP%%", TIMESTAMP_FMT.print(dtFirst));
queryStr = StringUtils.replace(queryStr, "%%TIMEBOUNDARY_RESPONSE_MAXTIME%%", TIMESTAMP_FMT.print(dtLast));
queryStr = StringUtils.replace(queryStr, "%%TIMEBOUNDARY_RESPONSE_MINTIME%%", TIMESTAMP_FMT.print(dtFirst));
queryStr = StringUtils.replace(queryStr, "%%TIMESERIES_QUERY_START%%", INTERVAL_FMT.print(dtFirst));
String queryEnd = INTERVAL_FMT.print(dtFirst.plusMinutes(MINUTES_TO_SEND + 2));
queryStr = StringUtils.replace(queryStr, "%%TIMESERIES_QUERY_END%%", queryEnd);
queryStr = StringUtils.replace(queryStr, "%%TIMESERIES_RESPONSE_TIMESTAMP%%", TIMESTAMP_FMT.print(dtFirst));
origin: prestodb/presto

private static final long DATE_MILLIS_UTC = new DateTime(2011, 5, 6, 0, 0, UTC).getMillis();
private static final long DATE_DAYS = TimeUnit.MILLISECONDS.toDays(DATE_MILLIS_UTC);
private static final String DATE_STRING = DateTimeFormat.forPattern("yyyy-MM-dd").withZoneUTC().print(DATE_MILLIS_UTC);
private static final Date SQL_DATE = new Date(UTC.getMillisKeepLocal(DateTimeZone.getDefault(), DATE_MILLIS_UTC));
private static final long TIMESTAMP = new DateTime(2011, 5, 6, 7, 8, 9, 123).getMillis();
private static final String TIMESTAMP_STRING = DateTimeFormat.forPattern("yyyy-MM-dd HH:mm:ss.SSS").print(TIMESTAMP);
origin: alibaba/fastjson

    formatter = defaultFormatter;
  } else {
    formatter = DateTimeFormat.forPattern(format);
  DateTimeZone offsetTime = DateTimeZone.forID(text);
  return (T) DateTimeFormat.forPattern(text);
  return (T) new DateTime(millis, DateTimeZone.forTimeZone(timeZone));
LocalDateTime localDateTime =  new LocalDateTime(millis, DateTimeZone.forTimeZone(timeZone));
if (type == LocalDateTime.class) {
  return (T) localDateTime;
origin: apache/incubator-gobblin

private void insertDailyPartition(Path dailyPartitionPath) throws Exception {
 String datasetPath = StringUtils.substringBeforeLast(dailyPartitionPath.toString(), Path.SEPARATOR + "daily");
 DateTime partition =
   DateTimeFormat.forPattern(DAILY_PARTITION_PATTERN).parseDateTime(
     StringUtils.substringAfter(dailyPartitionPath.toString(), "daily" + Path.SEPARATOR));
 PreparedStatement insert = connection.prepareStatement("INSERT INTO Daily_Partitions VALUES (?, ?, ?)");
 insert.setString(1, datasetPath);
 insert.setString(2, dailyPartitionPath.toString());
 insert.setTimestamp(3, new Timestamp(partition.getMillis()));
 insert.executeUpdate();
}
origin: apache/incubator-gobblin

DateTimeFormatter format = DateTimeFormat.forPattern("yyyy-MM-dd HH:mm:ss")
  .withZone(DateTimeZone.forTimeZone(TimeZone.getTimeZone("PST")));
  new DateTime(record.get("LastModifiedDate")).toString(format));
Assert.assertEquals(jsonRecord.get("date_type").getAsString(),
  new DateTime(record.get("date_type")).toString(format));
format = DateTimeFormat.forPattern("HH:mm:ss").withZone(DateTimeZone.forTimeZone(TimeZone.getTimeZone("PST")));
Assert.assertEquals(jsonRecord.get("time_type").getAsString(),
  new DateTime(record.get("time_type")).toString(format));
origin: joda-time/joda-time

/**
 * Output the date using the specified format pattern.
 *
 * @param pattern  the pattern specification, null means use <code>toString</code>
 * @param locale  Locale to use, null means default
 * @see org.joda.time.format.DateTimeFormat
 */
public String toString(String pattern, Locale locale) throws IllegalArgumentException {
  if (pattern == null) {
    return toString();
  }
  return DateTimeFormat.forPattern(pattern).withLocale(locale).print(this);
}
origin: jorgegil96/All-NBA

/**
 * Returns today's date formatted as "YYYY-MM-DD".
 */
public static String getTodayForHighlights() {
  DateTime dateTime = new DateTime(DateTimeZone.forTimeZone(
      TimeZone.getTimeZone("America/New_York")));
  return DateTimeFormat.forPattern("yyyy-MM-dd").print(dateTime);
}
origin: apache/incubator-gobblin

 List<GoogleWebmasterDataFetcher.Metric> requestedMetrics, JsonArray schemaJson,
 List<GoogleWebmasterDataFetcher> dataFetchers) {
DateTimeFormatter watermarkFormatter = DateTimeFormat.forPattern("yyyyMMddHHmmss");
_startDate = watermarkFormatter.parseDateTime(Long.toString(lowWatermark));
_expectedHighWaterMark = expectedHighWaterMark;
_expectedHighWaterMarkDate = watermarkFormatter.parseDateTime(Long.toString(expectedHighWaterMark));
log.info(String.format("Creating GoogleWebmasterExtractor for [%s, %s] for job %s.", _startDate.toString(),
  _expectedHighWaterMarkDate.toString(), wuState.getProp(ConfigurationKeys.SOURCE_ENTITY)));
  String startDate = dateFormatter.print(_startDate);
  String endDate = dateFormatter.print(_expectedHighWaterMarkDate);
  GoogleWebmasterExtractorIterator iterator =
origin: apache/incubator-gobblin

this.googleAnalyticsFormatter = DateTimeFormat.forPattern(DATE_FORMAT)
  .withZone(DateTimeZone.forID(wuState.getProp(SOURCE_TIMEZONE, DEFAULT_SOURCE_TIMEZONE)));
this.watermarkFormatter = DateTimeFormat.forPattern(WATERMARK_INPUTFORMAT)
  .withZone(DateTimeZone.forID(wuState.getProp(SOURCE_TIMEZONE, DEFAULT_SOURCE_TIMEZONE)));
DateTime nextWatermarkDateTime = googleAnalyticsFormatter.parseDateTime(createdReport.getEndDate()).plusDays(1);
nextWatermark = Long.parseLong(watermarkFormatter.print(nextWatermarkDateTime));
origin: spring-projects/spring-framework

@Test
public void dateToStringWithFormat() {
  JodaTimeFormatterRegistrar registrar = new JodaTimeFormatterRegistrar();
  registrar.setDateTimeFormatter(org.joda.time.format.DateTimeFormat.shortDateTime());
  setup(registrar);
  Date date = new Date();
  Object actual = this.conversionService.convert(date, TypeDescriptor.valueOf(Date.class), TypeDescriptor.valueOf(String.class));
  String expected = JodaTimeContextHolder.getFormatter(org.joda.time.format.DateTimeFormat.shortDateTime(), Locale.US).print(new DateTime(date));
  assertEquals(expected, actual);
}
origin: apache/incubator-gobblin

@Test
public void testWorksNoPrefix() throws IOException, DataRecordException {
 DatePartitionedAvroFileSource source = new DatePartitionedAvroFileSource();
 SourceState state = new SourceState();
 state.setProp(ConfigurationKeys.SOURCE_FILEBASED_FS_URI, ConfigurationKeys.LOCAL_FS_URI);
 state.setProp(ConfigurationKeys.EXTRACT_NAMESPACE_NAME_KEY, SOURCE_ENTITY);
 state.setProp(ConfigurationKeys.SOURCE_FILEBASED_DATA_DIRECTORY, OUTPUT_DIR + Path.SEPARATOR + SOURCE_ENTITY + Path.SEPARATOR + PREFIX);
 state.setProp(ConfigurationKeys.SOURCE_ENTITY, SOURCE_ENTITY);
 state.setProp(ConfigurationKeys.SOURCE_MAX_NUMBER_OF_PARTITIONS, 2);
 state.setProp("date.partitioned.source.partition.pattern", DATE_PATTERN);
 state.setProp("date.partitioned.source.min.watermark.value", DateTimeFormat.forPattern(DATE_PATTERN).print(
   this.startDateTime.minusMinutes(1)));
 state.setProp(ConfigurationKeys.EXTRACT_TABLE_TYPE_KEY, TableType.SNAPSHOT_ONLY);
 state.setProp("date.partitioned.source.partition.suffix", SUFFIX);
 //Read data partitioned by minutes, i.e each workunit is assigned records under the same YYYY/MM/dd/HH_mm directory
 List<WorkUnit> workunits = source.getWorkunits(state);
 Assert.assertEquals(workunits.size(), 4);
 verifyWorkUnits(workunits);
}
origin: qiurunze123/miaosha

public static Date strToDate(String dateTimeStr){
  DateTimeFormatter dateTimeFormatter = DateTimeFormat.forPattern(STANDARD_FORMAT);
  DateTime dateTime = dateTimeFormatter.parseDateTime(dateTimeStr);
  return dateTime.toDate();
}
org.joda.time.formatDateTimeFormat

Javadoc

Factory that creates instances of DateTimeFormatter from patterns and styles.

Datetime formatting is performed by the DateTimeFormatter class. Three classes provide factory methods to create formatters, and this is one. The others are ISODateTimeFormat and DateTimeFormatterBuilder.

This class provides two types of factory:

  • #forPattern(String) provides a DateTimeFormatter based on a pattern string that is mostly compatible with the JDK date patterns.
  • #forStyle(String) provides a DateTimeFormatter based on a two character style, representing short, medium, long and full.

For example, to use a patterm:

 
DateTime dt = new DateTime(); 
DateTimeFormatter fmt = DateTimeFormat.forPattern("MMMM, yyyy"); 
String str = fmt.print(dt); 
The pattern syntax is mostly compatible with java.text.SimpleDateFormat - time zone names cannot be parsed and a few more symbols are supported. All ASCII letters are reserved as pattern letters, which are defined as follows:
 
Symbol  Meaning                      Presentation  Examples 
------  -------                      ------------  ------- 
G       era                          text          AD 
C       century of era (>=0)         number        20 
Y       year of era (>=0)            year          1996 
x       weekyear                     year          1996 
w       week of weekyear             number        27 
e       day of week                  number        2 
E       day of week                  text          Tuesday; Tue 
y       year                         year          1996 
D       day of year                  number        189 
M       month of year                month         July; Jul; 07 
d       day of month                 number        10 
a       halfday of day               text          PM 
K       hour of halfday (0~11)       number        0 
h       clockhour of halfday (1~12)  number        12 
H       hour of day (0~23)           number        0 
k       clockhour of day (1~24)      number        24 
m       minute of hour               number        30 
s       second of minute             number        55 
S       fraction of second           number        978 
z       time zone                    text          Pacific Standard Time; PST 
Z       time zone offset/id          zone          -0800; -08:00; America/Los_Angeles 
'       escape for text              delimiter 
''      single quote                 literal       ' 
The count of pattern letters determine the format.

Text: If the number of pattern letters is 4 or more, the full form is used; otherwise a short or abbreviated form is used if available.

Number: The minimum number of digits. Shorter numbers are zero-padded to this amount.

Year: Numeric presentation for year and weekyear fields are handled specially. For example, if the count of 'y' is 2, the year will be displayed as the zero-based year of the century, which is two digits.

Month: 3 or over, use text, otherwise use number.

Zone: 'Z' outputs offset without a colon, 'ZZ' outputs the offset with a colon, 'ZZZ' or more outputs the zone id.

Zone names: Time zone names ('z') cannot be parsed.

Any characters in the pattern that are not in the ranges of ['a'..'z'] and ['A'..'Z'] will be treated as quoted text. For instance, characters like ':', '.', ' ', '#' and '?' will appear in the resulting time text even they are not embraced within single quotes.

DateTimeFormat is thread-safe and immutable, and the formatters it returns are as well.

Most used methods

  • forPattern
    Factory to create a formatter from a pattern string. The pattern string is described above in the cl
  • shortDateTime
    Creates a format that outputs a short datetime format. The format will change as you change the loca
  • appendPatternTo
    Parses the given pattern and appends the rules to the given DateTimeFormatterBuilder.
  • createFormatterForPattern
    Select a format from a custom pattern.
  • createFormatterForStyle
    Select a format from a two character style pattern. The first character is the date style, and the s
  • createFormatterForStyleIndex
    Gets the formatter for the specified style.
  • forStyle
    Factory to create a format from a two character style pattern. The first character is the date style
  • isNumericToken
    Returns true if token should be parsed as a numeric field.
  • mediumDate
    Creates a format that outputs a medium date format. The format will change as you change the locale
  • parsePatternTo
    Parses the given pattern and appends the rules to the given DateTimeFormatterBuilder.
  • parseToken
    Parses an individual token.
  • selectStyle
    Gets the JDK style code from the Joda code.
  • parseToken,
  • selectStyle,
  • fullDateTime,
  • shortTime,
  • createDateTimeFormatter,
  • mediumDateTime,
  • shortDate,
  • patternForStyle,
  • longDate,
  • longDateTime

Popular in Java

  • Creating JSON documents from java classes using gson
  • getContentResolver (Context)
  • setScale (BigDecimal)
  • runOnUiThread (Activity)
  • BufferedReader (java.io)
    Wraps an existing Reader and buffers the input. Expensive interaction with the underlying reader is
  • Collections (java.util)
    This class consists exclusively of static methods that operate on or return collections. It contains
  • Scanner (java.util)
    A parser that parses a text string of primitive types and strings with the help of regular expressio
  • Vector (java.util)
    Vector is an implementation of List, backed by an array and synchronized. All optional operations in
  • JFileChooser (javax.swing)
  • IOUtils (org.apache.commons.io)
    General IO stream manipulation utilities. This class provides static utility methods for input/outpu
  • Top 12 Jupyter Notebook extensions
Tabnine Logo
  • Products

    Search for Java codeSearch for JavaScript code
  • IDE Plugins

    IntelliJ IDEAWebStormVisual StudioAndroid StudioEclipseVisual Studio CodePyCharmSublime TextPhpStormVimGoLandRubyMineEmacsJupyter NotebookJupyter LabRiderDataGripAppCode
  • Company

    About UsContact UsCareers
  • Resources

    FAQBlogTabnine AcademyTerms of usePrivacy policyJava Code IndexJavascript Code Index
Get Tabnine for your IDE now