Java Code Examples for java.time.format.DateTimeFormatter#ofLocalizedDateTime()

The following examples show how to use java.time.format.DateTimeFormatter#ofLocalizedDateTime() . 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 File: TimeZones.java    From JavaSE8-Features with GNU General Public License v3.0 7 votes vote down vote up
public static void main(String[] args) {

        DateTimeFormatter dtf = DateTimeFormatter.ofLocalizedDateTime(FormatStyle.SHORT);
        LocalDateTime currentDT = LocalDateTime.now();
        System.out.println(dtf.format(currentDT));
        
        ZonedDateTime gmt = ZonedDateTime.now(ZoneId.of("GMT+0"));
        System.out.println(dtf.format(gmt));
        
        ZonedDateTime ny = ZonedDateTime.now(ZoneId.of("America/New_York"));
        System.out.println(dtf.format(ny));
        
        Set<String> zones = ZoneId.getAvailableZoneIds();
        Predicate<String> condition = str -> str.contains("London");
        zones.forEach(z -> {
            if(condition.test(z))
            System.out.println(z);
        });

    }
 
Example 2
Source File: ClockUtils.java    From mars-sim with GNU General Public License v3.0 6 votes vote down vote up
/**
 * Convert from the number of seconds since 1970 Jan 1
 * 
 * @return String the Mars date in standard format yy-month-dd
 */
public static String convertSecs2MarsDate(long s) {
	// Based on
	// https://stackoverflow.com/questions/8262333/convert-epoch-seconds-to-date-and-time-format-in-java#
	Instant instant = Instant.ofEpochSecond(s);

	ZoneId zoneId = ZoneId.of("Etc/UTC");
	ZonedDateTime zdt = instant.atZone(zoneId);

	DateTimeFormatter formatter = DateTimeFormatter.ofLocalizedDateTime(FormatStyle.FULL);
	formatter = formatter.withLocale(Locale.US);
	String output = zdt.format(formatter);

	return output;

}
 
Example 3
Source File: ODateLabel.java    From Orienteer with Apache License 2.0 5 votes vote down vote up
private DateTimeFormatter getFormatter(ZoneId zoneId) {
    DateTimeFormatter formatter;
    if (showTime) {
        formatter = DateTimeFormatter.ofLocalizedDateTime(FormatStyle.MEDIUM);
    } else formatter = DateTimeFormatter.ofLocalizedDate(FormatStyle.MEDIUM);

    return formatter.withLocale(getLocale())
    				.withZone(convertTimeZone&&zoneId!=null
    									?zoneId
    									:OrienteerWebSession.get().getDatabase().getStorage()
    												.getConfiguration().getTimeZone().toZoneId());
}
 
Example 4
Source File: ZonedDateTimeAxis.java    From constellation with Apache License 2.0 5 votes vote down vote up
@Override
protected String getTickMarkLabel(ZonedDateTime datetime) {
    final StringConverter<ZonedDateTime> converter = getTickLabelFormatter();
    if (converter != null) {
        return converter.toString(datetime);
    }

    final DateTimeFormatter formatter;
    if (actualInterval.interval == ChronoUnit.YEARS && datetime.getMonth() == Month.JANUARY && datetime.getDayOfMonth() == 1) {
        formatter = DateTimeFormatter.ofPattern("yyyy");
    } else if (actualInterval.interval == ChronoUnit.MONTHS && datetime.getDayOfMonth() == 1) {
        formatter = DateTimeFormatter.ofPattern("MMM yy");
    } else {
        switch (actualInterval.interval) {
            case DAYS:
            case WEEKS:
            case HOURS:
            case MINUTES:
                formatter = DateTimeFormatter.ofLocalizedDateTime(FormatStyle.SHORT);
                break;
            case SECONDS:
                formatter = DateTimeFormatter.ofLocalizedDateTime(FormatStyle.MEDIUM);
                break;
            case MILLIS:
                formatter = DateTimeFormatter.ofLocalizedDateTime(FormatStyle.FULL);
                break;
            default:
                formatter = DateTimeFormatter.ofLocalizedDateTime(FormatStyle.MEDIUM);
                break;
        }
    }
    return formatter.format(datetime);
}
 
Example 5
Source File: JinjavaInterpreterResolver.java    From jinjava with Apache License 2.0 5 votes vote down vote up
private static DateTimeFormatter getFormatter(
  JinjavaInterpreter interpreter,
  FormattedDate d
) {
  if (!StringUtils.isBlank(d.getFormat())) {
    try {
      return StrftimeFormatter.formatter(
        d.getFormat(),
        interpreter.getConfig().getLocale()
      );
    } catch (IllegalArgumentException e) {
      interpreter.addError(
        new TemplateError(
          ErrorType.WARNING,
          ErrorReason.SYNTAX_ERROR,
          ErrorItem.OTHER,
          e.getMessage(),
          null,
          interpreter.getLineNumber(),
          -1,
          null,
          BasicTemplateErrorCategory.UNKNOWN_DATE,
          ImmutableMap.of(
            "date",
            d.getDate().toString(),
            "exception",
            e.getMessage(),
            "lineNumber",
            String.valueOf(interpreter.getLineNumber())
          )
        )
      );
    }
  }

  return DateTimeFormatter.ofLocalizedDateTime(FormatStyle.MEDIUM);
}
 
Example 6
Source File: DateTimeFormatterFactory.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
/**
 * Create a new {@code DateTimeFormatter} using this factory.
 * <p>If no specific pattern or style has been defined,
 * the supplied {@code fallbackFormatter} will be used.
 * @param fallbackFormatter the fall-back formatter to use when no specific
 * factory properties have been set (can be {@code null}).
 * @return a new date time formatter
 */
public DateTimeFormatter createDateTimeFormatter(DateTimeFormatter fallbackFormatter) {
	DateTimeFormatter dateTimeFormatter = null;
	if (StringUtils.hasLength(this.pattern)) {
		dateTimeFormatter = DateTimeFormatter.ofPattern(this.pattern);
	}
	else if (this.iso != null && this.iso != ISO.NONE) {
		switch (this.iso) {
			case DATE:
				dateTimeFormatter = DateTimeFormatter.ISO_DATE;
				break;
			case TIME:
				dateTimeFormatter = DateTimeFormatter.ISO_TIME;
				break;
			case DATE_TIME:
				dateTimeFormatter = DateTimeFormatter.ISO_DATE_TIME;
				break;
			case NONE:
				/* no-op */
				break;
			default:
				throw new IllegalStateException("Unsupported ISO format: " + this.iso);
		}
	}
	else if (this.dateStyle != null && this.timeStyle != null) {
		dateTimeFormatter = DateTimeFormatter.ofLocalizedDateTime(this.dateStyle, this.timeStyle);
	}
	else if (this.dateStyle != null) {
		dateTimeFormatter = DateTimeFormatter.ofLocalizedDate(this.dateStyle);
	}
	else if (this.timeStyle != null) {
		dateTimeFormatter = DateTimeFormatter.ofLocalizedTime(this.timeStyle);
	}

	if (dateTimeFormatter != null && this.timeZone != null) {
		dateTimeFormatter = dateTimeFormatter.withZone(this.timeZone.toZoneId());
	}
	return (dateTimeFormatter != null ? dateTimeFormatter : fallbackFormatter);
}
 
Example 7
Source File: DateTimeFormatterRegistrar.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
private DateTimeFormatter getFallbackFormatter(Type type) {
	switch (type) {
		case DATE: return DateTimeFormatter.ofLocalizedDate(FormatStyle.SHORT);
		case TIME: return DateTimeFormatter.ofLocalizedTime(FormatStyle.SHORT);
		default: return DateTimeFormatter.ofLocalizedDateTime(FormatStyle.SHORT);
	}
}
 
Example 8
Source File: DateTimeFormatterRegistrar.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
private DateTimeFormatter getFallbackFormatter(Type type) {
	switch (type) {
		case DATE: return DateTimeFormatter.ofLocalizedDate(FormatStyle.SHORT);
		case TIME: return DateTimeFormatter.ofLocalizedTime(FormatStyle.SHORT);
		default: return DateTimeFormatter.ofLocalizedDateTime(FormatStyle.SHORT);
	}
}
 
Example 9
Source File: DateTimeFormatterDemo.java    From SA47 with The Unlicense 5 votes vote down vote up
public static void main(String[] args) {
	// TODO Auto-generated method stub
	 DateTimeFormatter formatter1 = DateTimeFormatter
                .ofLocalizedDateTime(FormatStyle.MEDIUM);
        LocalDateTime example = LocalDateTime.of(
                2000, 3, 19, 10, 56, 59);
        System.out.println("Format 1: " + example
                .format(formatter1));        
        DateTimeFormatter formatter2 = DateTimeFormatter
                .ofPattern("MMMM dd, yyyy HH:mm:ss");
        System.out.println("Format 2: " + 
                example.format(formatter2));

}
 
Example 10
Source File: DateTimeFormatterFactory.java    From java-technology-stack with MIT License 5 votes vote down vote up
/**
 * Create a new {@code DateTimeFormatter} using this factory.
 * <p>If no specific pattern or style has been defined,
 * the supplied {@code fallbackFormatter} will be used.
 * @param fallbackFormatter the fall-back formatter to use
 * when no specific factory properties have been set
 * @return a new date time formatter
 */
public DateTimeFormatter createDateTimeFormatter(DateTimeFormatter fallbackFormatter) {
	DateTimeFormatter dateTimeFormatter = null;
	if (StringUtils.hasLength(this.pattern)) {
		// Using strict parsing to align with Joda-Time and standard DateFormat behavior:
		// otherwise, an overflow like e.g. Feb 29 for a non-leap-year wouldn't get rejected.
		// However, with strict parsing, a year digit needs to be specified as 'u'...
		String patternToUse = StringUtils.replace(this.pattern, "yy", "uu");
		dateTimeFormatter = DateTimeFormatter.ofPattern(patternToUse).withResolverStyle(ResolverStyle.STRICT);
	}
	else if (this.iso != null && this.iso != ISO.NONE) {
		switch (this.iso) {
			case DATE:
				dateTimeFormatter = DateTimeFormatter.ISO_DATE;
				break;
			case TIME:
				dateTimeFormatter = DateTimeFormatter.ISO_TIME;
				break;
			case DATE_TIME:
				dateTimeFormatter = DateTimeFormatter.ISO_DATE_TIME;
				break;
			default:
				throw new IllegalStateException("Unsupported ISO format: " + this.iso);
		}
	}
	else if (this.dateStyle != null && this.timeStyle != null) {
		dateTimeFormatter = DateTimeFormatter.ofLocalizedDateTime(this.dateStyle, this.timeStyle);
	}
	else if (this.dateStyle != null) {
		dateTimeFormatter = DateTimeFormatter.ofLocalizedDate(this.dateStyle);
	}
	else if (this.timeStyle != null) {
		dateTimeFormatter = DateTimeFormatter.ofLocalizedTime(this.timeStyle);
	}

	if (dateTimeFormatter != null && this.timeZone != null) {
		dateTimeFormatter = dateTimeFormatter.withZone(this.timeZone.toZoneId());
	}
	return (dateTimeFormatter != null ? dateTimeFormatter : fallbackFormatter);
}
 
Example 11
Source File: DateTimeFormatterRegistrar.java    From java-technology-stack with MIT License 5 votes vote down vote up
private DateTimeFormatter getFallbackFormatter(Type type) {
	switch (type) {
		case DATE: return DateTimeFormatter.ofLocalizedDate(FormatStyle.SHORT);
		case TIME: return DateTimeFormatter.ofLocalizedTime(FormatStyle.SHORT);
		default: return DateTimeFormatter.ofLocalizedDateTime(FormatStyle.SHORT);
	}
}
 
Example 12
Source File: DateTimeFormatterRegistrar.java    From spring-analysis-note with MIT License 5 votes vote down vote up
private DateTimeFormatter getFallbackFormatter(Type type) {
	switch (type) {
		case DATE: return DateTimeFormatter.ofLocalizedDate(FormatStyle.SHORT);
		case TIME: return DateTimeFormatter.ofLocalizedTime(FormatStyle.SHORT);
		default: return DateTimeFormatter.ofLocalizedDateTime(FormatStyle.SHORT);
	}
}
 
Example 13
Source File: LogOutputSpec.java    From jkube with Eclipse Public License 2.0 5 votes vote down vote up
public LogOutputSpecBuilder timeFormatterString(String formatOrConstant) {
    if (formatOrConstant == null || formatOrConstant.equalsIgnoreCase("NONE")
            || formatOrConstant.equalsIgnoreCase("FALSE")) {
        timeFormatter = null;
    } else if (formatOrConstant.length() == 0 || formatOrConstant.equalsIgnoreCase("DEFAULT")) {
        timeFormatter = DateTimeFormatter.ofPattern(DEFAULT_TIMESTAMP_PATTERN);
    } else if (formatOrConstant.equalsIgnoreCase("ISO8601")) {
        timeFormatter = DateTimeFormatter.ISO_DATE_TIME;
    } else if (formatOrConstant.equalsIgnoreCase("SHORT")) {
        timeFormatter = DateTimeFormatter.ofLocalizedDateTime(FormatStyle.SHORT);
    } else if (formatOrConstant.equalsIgnoreCase("MEDIUM")) {
        timeFormatter = DateTimeFormatter.ofLocalizedDateTime(FormatStyle.MEDIUM);
    } else if (formatOrConstant.equalsIgnoreCase("LONG")) {
        timeFormatter = DateTimeFormatter.ofLocalizedDateTime(FormatStyle.LONG);
    } else if (formatOrConstant.equalsIgnoreCase("FULL")) {
        timeFormatter = DateTimeFormatter.ofLocalizedDateTime(FormatStyle.FULL);
    } else {
        try {
            timeFormatter = DateTimeFormatter.ofPattern(formatOrConstant);
        } catch (IllegalArgumentException exp) {
            throw new IllegalArgumentException(
                    "Cannot parse log date specification '" + formatOrConstant + "'." +
                            "Must be either DEFAULT, NONE, ISO8601, SHORT, MEDIUM, LONG, FULL or a " +
                            "format string parseable by DateTimeFormat. See " +
                            "https://docs.oracle.com/javase/8/docs/api/java/time/format/DateTimeFormatter.html");
        }
    }
    return this;
}
 
Example 14
Source File: Change.java    From PreferencesFX with Apache License 2.0 4 votes vote down vote up
public String getTimestamp() {
  DateTimeFormatter formatter = DateTimeFormatter.ofLocalizedDateTime(FormatStyle.MEDIUM);
  return timestamp.format(formatter);
}
 
Example 15
Source File: TypeConverter.java    From sailfish-core with Apache License 2.0 4 votes vote down vote up
public static String getString(LocalDateTime value) {
    DateTimeFormatter formatter = DateTimeFormatter.ofLocalizedDateTime(FormatStyle.LONG, FormatStyle.LONG);
    return value.format(formatter);
}
 
Example 16
Source File: DateTimeFormatterFactory.java    From lams with GNU General Public License v2.0 4 votes vote down vote up
/**
 * Create a new {@code DateTimeFormatter} using this factory.
 * <p>If no specific pattern or style has been defined,
 * the supplied {@code fallbackFormatter} will be used.
 * @param fallbackFormatter the fall-back formatter to use when no specific
 * factory properties have been set (can be {@code null}).
 * @return a new date time formatter
 */
public DateTimeFormatter createDateTimeFormatter(DateTimeFormatter fallbackFormatter) {
	DateTimeFormatter dateTimeFormatter = null;
	if (StringUtils.hasLength(this.pattern)) {
		// Using strict parsing to align with Joda-Time and standard DateFormat behavior:
		// otherwise, an overflow like e.g. Feb 29 for a non-leap-year wouldn't get rejected.
		// However, with strict parsing, a year digit needs to be specified as 'u'...
		String patternToUse = this.pattern.replace("yy", "uu");
		dateTimeFormatter = DateTimeFormatter.ofPattern(patternToUse).withResolverStyle(ResolverStyle.STRICT);
	}
	else if (this.iso != null && this.iso != ISO.NONE) {
		switch (this.iso) {
			case DATE:
				dateTimeFormatter = DateTimeFormatter.ISO_DATE;
				break;
			case TIME:
				dateTimeFormatter = DateTimeFormatter.ISO_TIME;
				break;
			case DATE_TIME:
				dateTimeFormatter = DateTimeFormatter.ISO_DATE_TIME;
				break;
			case NONE:
				/* no-op */
				break;
			default:
				throw new IllegalStateException("Unsupported ISO format: " + this.iso);
		}
	}
	else if (this.dateStyle != null && this.timeStyle != null) {
		dateTimeFormatter = DateTimeFormatter.ofLocalizedDateTime(this.dateStyle, this.timeStyle);
	}
	else if (this.dateStyle != null) {
		dateTimeFormatter = DateTimeFormatter.ofLocalizedDate(this.dateStyle);
	}
	else if (this.timeStyle != null) {
		dateTimeFormatter = DateTimeFormatter.ofLocalizedTime(this.timeStyle);
	}

	if (dateTimeFormatter != null && this.timeZone != null) {
		dateTimeFormatter = dateTimeFormatter.withZone(this.timeZone.toZoneId());
	}
	return (dateTimeFormatter != null ? dateTimeFormatter : fallbackFormatter);
}
 
Example 17
Source File: DateTimeFormatterFactoryTests.java    From spring-analysis-note with MIT License 4 votes vote down vote up
@Test
public void createDateTimeFormatterWithFallback() {
	DateTimeFormatter fallback = DateTimeFormatter.ofLocalizedDateTime(FormatStyle.LONG);
	DateTimeFormatter formatter = factory.createDateTimeFormatter(fallback);
	assertThat(formatter, is(sameInstance(fallback)));
}
 
Example 18
Source File: DateTimeFormatterFactoryTests.java    From spring4-understanding with Apache License 2.0 4 votes vote down vote up
@Test
public void createDateTimeFormatterWithFallback() throws Exception {
	DateTimeFormatter fallback = DateTimeFormatter.ofLocalizedDateTime(FormatStyle.LONG);
	DateTimeFormatter formatter = factory.createDateTimeFormatter(fallback);
	assertThat(formatter, is(sameInstance(fallback)));
}
 
Example 19
Source File: OffsetDateTimeDatatype.java    From cuba with Apache License 2.0 4 votes vote down vote up
@Override
protected DateTimeFormatter getDateTimeFormatter() {
    return DateTimeFormatter.ofLocalizedDateTime(FormatStyle.SHORT);
}
 
Example 20
Source File: LocalDateTimeRenderer.java    From flow with Apache License 2.0 2 votes vote down vote up
/**
 * Creates a new LocalDateTimeRenderer.
 * <p>
 * The renderer is configured to render with the format style
 * {@code FormatStyle.LONG} for the date and {@code FormatStyle.SHORT} for
 * time, with an empty string as its null representation.
 * 
 * @param valueProvider
 *            the callback to provide a {@link LocalDateTime} to the
 *            renderer, not <code>null</code>
 *
 * @see <a href=
 *      "https://docs.oracle.com/javase/8/docs/api/java/time/format/FormatStyle.html#LONG">
 *      FormatStyle.LONG</a>
 * @see <a href=
 *      "https://docs.oracle.com/javase/8/docs/api/java/time/format/FormatStyle.html#SHORT">
 *      FormatStyle.SHORT</a>
 */
public LocalDateTimeRenderer(
        ValueProvider<SOURCE, LocalDateTime> valueProvider) {
    this(valueProvider, DateTimeFormatter
            .ofLocalizedDateTime(FormatStyle.LONG, FormatStyle.SHORT), "");
}