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

The following examples show how to use java.time.format.DateTimeFormatter#ofPattern() . 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: HibernateTimeZoneTest.java    From Spring-5.0-Projects with MIT License 6 votes vote down vote up
@Before
public void setup() {
    dateTimeWrapper = new DateTimeWrapper();
    dateTimeWrapper.setInstant(Instant.parse("2014-11-12T05:50:00.0Z"));
    dateTimeWrapper.setLocalDateTime(LocalDateTime.parse("2014-11-12T07:50:00.0"));
    dateTimeWrapper.setOffsetDateTime(OffsetDateTime.parse("2011-12-14T08:30:00.0Z"));
    dateTimeWrapper.setZonedDateTime(ZonedDateTime.parse("2011-12-14T08:30:00.0Z"));
    dateTimeWrapper.setLocalTime(LocalTime.parse("14:30:00"));
    dateTimeWrapper.setOffsetTime(OffsetTime.parse("14:30:00+02:00"));
    dateTimeWrapper.setLocalDate(LocalDate.parse("2016-09-10"));

    dateTimeFormatter = DateTimeFormatter
        .ofPattern("yyyy-MM-dd HH:mm:ss.S")
        .withZone(ZoneId.of("UTC"));

    timeFormatter = DateTimeFormatter
        .ofPattern("HH:mm:ss")
        .withZone(ZoneId.of("UTC"));

    dateFormatter = DateTimeFormatter
        .ofPattern("yyyy-MM-dd");
}
 
Example 2
Source File: DateUtils.java    From momo-cloud-permission with Apache License 2.0 5 votes vote down vote up
/**
 * string 转 LocalDateTime
 *
 * @param dateStr 例:"2017-08-11 01:00:00"
 * @param format  例:"yyyy-MM-dd HH:mm:ss"
 * @return
 */
public static LocalDateTime stringToLocalDateTime(String dateStr, String format) {
    try {
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern(format);
        return LocalDateTime.parse(dateStr, formatter);
    } catch (DateTimeParseException e) {
        e.printStackTrace();
    }
    return null;
}
 
Example 3
Source File: TimeServiceImpl.java    From NoraUi with GNU Affero General Public License v3.0 5 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Override
public String getDayMinusXBusinessDay(int offsetDay, String zone, String formatter) {
    DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern(formatter);
    ZonedDateTime date = ZonedDateTime.now(ZoneId.of(zone)).minusDays(offsetDay);
    if ("SATURDAY".equals(date.getDayOfWeek().toString())) {
        date = date.minusDays(1);
    } else if ("SUNDAY".equals(date.getDayOfWeek().toString())) {
        date = date.minusDays(2);
    }
    return date.format(dateTimeFormatter);
}
 
Example 4
Source File: TestDateTimeFormatter.java    From jdk8u-jdk with GNU General Public License v2.0 5 votes vote down vote up
@Test
public void test_parsed_toString_resolvedDateTime() {
    DateTimeFormatter f = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
    TemporalAccessor temporal = f.parse("2010-06-30 11:30:56");
    String msg = temporal.toString();
    assertTrue(msg.contains("2010-06-30"), msg);
    assertTrue(msg.contains("11:30:56"), msg);
}
 
Example 5
Source File: DateTimeFormatterUnitTest.java    From tutorials with MIT License 5 votes vote down vote up
@Test
public void shouldPrintFormattedTimePM() {
    String timeColonPattern = "hh:mm:ss a";
    DateTimeFormatter timeColonFormatter = DateTimeFormatter.ofPattern(timeColonPattern);
    LocalTime colonTime = LocalTime.of(17, 35, 50);
    Assert.assertEquals("05:35:50 PM", timeColonFormatter.format(colonTime));
}
 
Example 6
Source File: IndexServiceOnlineImpl.java    From cloudstreetmarket.com with GNU General Public License v3.0 5 votes vote down vote up
private void updateChartIndexFromYahoo(Index index, ChartType type, ChartHistoSize histoSize, ChartHistoMovingAverage histoAverage,
		ChartHistoTimeSpan histoPeriod, Integer intradayWidth, Integer intradayHeight) {
	
	Preconditions.checkNotNull(index, "index must not be null!");
	Preconditions.checkNotNull(type, "ChartType must not be null!");
	
	String guid = AuthenticationUtil.getPrincipal().getUsername();
	SocialUser socialUser = usersConnectionRepository.getRegisteredSocialUser(guid);
	if(socialUser == null){
		return;
	}
	
	String token = socialUser.getAccessToken();
	
       Connection<Yahoo2> connection = connectionRepository.getPrimaryConnection(Yahoo2.class);

       if (connection != null) {
		byte[] yahooChart = connection.getApi().financialOperations().getYahooChart(index.getId(), type, histoSize, histoAverage, histoPeriod, intradayWidth, intradayHeight, token);
		
		DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd_HHmm");
		LocalDateTime dateTime = LocalDateTime.now();
		String formattedDateTime = dateTime.format(formatter); // "1986-04-08_1230"
		String imageName = index.getId().toLowerCase()+"_"+type.name().toLowerCase()+"_"+formattedDateTime+".png";
    	String pathToYahooPicture = env.getProperty("user.home").concat(env.getProperty("pictures.yahoo.path")).concat(File.separator+imageName);
    	
           try {
               Path newPath = Paths.get(pathToYahooPicture);
               Files.write(newPath, yahooChart, StandardOpenOption.CREATE);
           } catch (IOException e) {
               throw new Error("Storage of " + pathToYahooPicture+ " failed", e);
           }
           
           ChartIndex chartIndex = new ChartIndex(index, type, histoSize, histoAverage, histoPeriod, intradayWidth, intradayHeight, pathToYahooPicture);
           chartIndexRepository.save(chartIndex);
       }
}
 
Example 7
Source File: TCKOffsetDateTime.java    From openjdk-jdk8u with GNU General Public License v2.0 5 votes vote down vote up
@Test
public void factory_parse_formatter() {
    DateTimeFormatter f = DateTimeFormatter.ofPattern("y M d H m s XXX");
    OffsetDateTime test = OffsetDateTime.parse("2010 12 3 11 30 0 +01:00", f);
    assertEquals(test, OffsetDateTime.of(LocalDate.of(2010, 12, 3), LocalTime.of(11, 30), ZoneOffset.ofHours(1)));
}
 
Example 8
Source File: Solution.java    From JavaRushTasks with MIT License 5 votes vote down vote up
public static String weekDayOfBirthday(String birthday, String year) {
    //напишите тут ваш код
    DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("d.M.yyyy", Locale.ITALIAN);
    LocalDate localDate = LocalDate.parse(birthday, dateTimeFormatter);
    localDate = localDate.with(Year.parse(year));
    return DateTimeFormatter.ofLocalizedDate(FormatStyle.FULL).withLocale(Locale.ITALIAN).format(localDate).split(" ")[0];

}
 
Example 9
Source File: TCKLocalDate.java    From j2objc with Apache License 2.0 4 votes vote down vote up
@Test(expected=NullPointerException.class)
public void factory_parse_formatter_nullText() {
    DateTimeFormatter f = DateTimeFormatter.ofPattern("y M d");
    LocalDate.parse((String) null, f);
}
 
Example 10
Source File: DiffDateExpressionProcessor.java    From vividus with Apache License 2.0 4 votes vote down vote up
private ZonedDateTime getZonedDateTime(Matcher expressionMatcher, int inputDateGroup, int inputFormatGroup)
{
    DateTimeFormatter inputFormat = DateTimeFormatter
            .ofPattern(normalize(expressionMatcher.group(inputFormatGroup)));
    return dateUtils.parseDateTime(normalize(expressionMatcher.group(inputDateGroup)), inputFormat);
}
 
Example 11
Source File: DateUtil.java    From permission with MIT License 4 votes vote down vote up
public static String formatFullTime(LocalDateTime localDateTime, String pattern) {
    DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern(pattern);
    return localDateTime.format(dateTimeFormatter);
}
 
Example 12
Source File: TCKDateTimeFormatters.java    From openjdk-8 with GNU General Public License v2.0 4 votes vote down vote up
@Test(expectedExceptions=NullPointerException.class)
public void test_pattern_String_null() {
    DateTimeFormatter.ofPattern(null);
}
 
Example 13
Source File: TCKZonedDateTime.java    From jdk8u_jdk with GNU General Public License v2.0 4 votes vote down vote up
@Test(expectedExceptions=NullPointerException.class)
public void factory_parse_formatter_nullText() {
    DateTimeFormatter f = DateTimeFormatter.ofPattern("y M d H m s");
    ZonedDateTime.parse((String) null, f);
}
 
Example 14
Source File: TCKDateTimeFormatter.java    From jdk8u_jdk with GNU General Public License v2.0 4 votes vote down vote up
@Test
public void test_parseBest_secondOption() throws Exception {
    DateTimeFormatter test = DateTimeFormatter.ofPattern("yyyy-MM-dd[ HH:mm[XXX]]");
    TemporalAccessor result = test.parseBest("2011-06-30", ZonedDateTime::from, LocalDate::from);
    assertEquals(result, LocalDate.of(2011, 6, 30));
}
 
Example 15
Source File: TimestampToString.java    From ksql-fork-with-deep-learning-function with Apache License 2.0 4 votes vote down vote up
private void ensureInitialized(final Object[] args) {
  if (threadSafeFormatter == null) {
    threadSafeFormatter = DateTimeFormatter.ofPattern(args[1].toString());
  }
}
 
Example 16
Source File: TimerControlTileSkin.java    From OEE-Designer with MIT License 4 votes vote down vote up
@Override protected void initGraphics() {
    super.initGraphics();

    currentValueListener = o -> {
        if (tile.isRunning()) { return; } // Update time only if clock is not already running
        updateTime(ZonedDateTime.ofInstant(Instant.ofEpochSecond(tile.getCurrentTime()), ZoneId.of(ZoneId.systemDefault().getId())));
    };
    timeListener         = o -> updateTime(tile.getTime());

    dateFormatter = DateTimeFormatter.ofPattern("EE d", tile.getLocale());

    sectionMap   = new HashMap<>(tile.getTimeSections().size());
    for (TimeSection section : tile.getTimeSections()) { sectionMap.put(section, new Arc()); }

    minuteRotate = new Rotate();
    hourRotate   = new Rotate();
    secondRotate = new Rotate();

    sectionsPane = new Pane();
    sectionsPane.getChildren().addAll(sectionMap.values());
    Helper.enableNode(sectionsPane, tile.getSectionsVisible());

    minuteTickMarks = new Path();
    minuteTickMarks.setFillRule(FillRule.EVEN_ODD);
    minuteTickMarks.setFill(null);
    minuteTickMarks.setStroke(tile.getMinuteColor());
    minuteTickMarks.setStrokeLineCap(StrokeLineCap.ROUND);

    hourTickMarks = new Path();
    hourTickMarks.setFillRule(FillRule.EVEN_ODD);
    hourTickMarks.setFill(null);
    hourTickMarks.setStroke(tile.getHourColor());
    hourTickMarks.setStrokeLineCap(StrokeLineCap.ROUND);

    hour = new Rectangle(3, 60);
    hour.setArcHeight(3);
    hour.setArcWidth(3);
    hour.setStroke(tile.getHourColor());
    hour.getTransforms().setAll(hourRotate);

    minute = new Rectangle(3, 96);
    minute.setArcHeight(3);
    minute.setArcWidth(3);
    minute.setStroke(tile.getMinuteColor());
    minute.getTransforms().setAll(minuteRotate);

    second = new Rectangle(1, 96);
    second.setArcHeight(1);
    second.setArcWidth(1);
    second.setStroke(tile.getSecondColor());
    second.getTransforms().setAll(secondRotate);
    second.setVisible(tile.isSecondsVisible());
    second.setManaged(tile.isSecondsVisible());

    knob = new Circle(PREFERRED_WIDTH * 0.5, PREFERRED_HEIGHT * 0.5, 4.5);
    knob.setStroke(Color.web("#282a3280"));

    dropShadow = new DropShadow();
    dropShadow.setColor(Color.rgb(0, 0, 0, 0.25));
    dropShadow.setBlurType(BlurType.TWO_PASS_BOX);
    dropShadow.setRadius(0.015 * PREFERRED_WIDTH);
    dropShadow.setOffsetY(0.015 * PREFERRED_WIDTH);

    shadowGroupHour   = new Group(hour);
    shadowGroupMinute = new Group(minute);
    shadowGroupSecond = new Group(second, knob);

    shadowGroupHour.setEffect(tile.isShadowsEnabled() ? dropShadow : null);
    shadowGroupMinute.setEffect(tile.isShadowsEnabled() ? dropShadow : null);
    shadowGroupSecond.setEffect(tile.isShadowsEnabled() ? dropShadow : null);

    titleText = new Text("");
    titleText.setTextOrigin(VPos.TOP);
    Helper.enableNode(titleText, !tile.getTitle().isEmpty());

    amPmText = new Text(tile.getTime().get(ChronoField.AMPM_OF_DAY) == 0 ? "AM" : "PM");

    dateText = new Text("");
    Helper.enableNode(dateText, tile.isDateVisible());

    text = new Text("");
    Helper.enableNode(text, tile.isTextVisible());

    getPane().getChildren().addAll(sectionsPane, hourTickMarks, minuteTickMarks, titleText, amPmText, dateText, text, shadowGroupHour, shadowGroupMinute, shadowGroupSecond);
}
 
Example 17
Source File: Util.java    From EnchantmentsEnhance with GNU General Public License v3.0 4 votes vote down vote up
public static String getCurrentDate() {
    DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyy/MM/dd");
    LocalDate localDate = LocalDate.now();
    return dtf.format(localDate);
}
 
Example 18
Source File: TemporalRoundingTest.java    From phoebus with Eclipse Public License 1.0 4 votes vote down vote up
@Test
public void testTimeRounding()
{
    final DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.SSS");
    final ZoneId zone = ZoneId.of("America/New_York");

    ZonedDateTime time = ZonedDateTime.of(2014, 10, 25, 13, 40, 1, Duration.ofMillis(42).getNano(), zone);
    assertThat(formatter.format(time), equalTo("2014-10-25 13:40:01.042"));

    assertThat(formatter.format(time.with(nextOrSameMidnight)),
            equalTo("2014-10-26 00:00:00.000"));

    assertThat(formatter.format(time.with(zonedDateTimerRoundedToNextOrSame(ChronoUnit.MILLIS, 1))),
            equalTo("2014-10-25 13:40:01.042"));
    assertThat(formatter.format(time.with(zonedDateTimerRoundedToNextOrSame(ChronoUnit.MILLIS, 50))),
            equalTo("2014-10-25 13:40:01.050"));
    assertThat(formatter.format(time.with(zonedDateTimerRoundedToNextOrSame(ChronoUnit.MILLIS, 500))),
            equalTo("2014-10-25 13:40:01.500"));

    // Truncating side-effect of rounding by 0
    assertThat(formatter.format(time.with(zonedDateTimerRoundedToNextOrSame(ChronoUnit.SECONDS, 0))),
            equalTo("2014-10-25 13:40:01.000"));

    assertThat(formatter.format(time.with(zonedDateTimerRoundedToNextOrSame(ChronoUnit.SECONDS, 1))),
            equalTo("2014-10-25 13:40:02.000"));
    assertThat(formatter.format(time.with(zonedDateTimerRoundedToNextOrSame(ChronoUnit.SECONDS, 5))),
            equalTo("2014-10-25 13:40:05.000"));
    assertThat(formatter.format(time.with(zonedDateTimerRoundedToNextOrSame(ChronoUnit.SECONDS, 8))),
            equalTo("2014-10-25 13:40:08.000"));
    assertThat(formatter.format(time.with(zonedDateTimerRoundedToNextOrSame(ChronoUnit.SECONDS, 30))),
            equalTo("2014-10-25 13:40:30.000"));
    assertThat(formatter.format(time.with(zonedDateTimerRoundedToNextOrSame(ChronoUnit.SECONDS, 60))),
            equalTo("2014-10-25 13:41:00.000"));

    assertThat(formatter.format(time.with(zonedDateTimerRoundedToNextOrSame(ChronoUnit.MINUTES, 1))),
            equalTo("2014-10-25 13:41:00.000"));
    assertThat(formatter.format(time.with(zonedDateTimerRoundedToNextOrSame(ChronoUnit.MINUTES, 5))),
            equalTo("2014-10-25 13:45:00.000"));
    assertThat(formatter.format(time.with(zonedDateTimerRoundedToNextOrSame(ChronoUnit.MINUTES, 30))),
            equalTo("2014-10-25 14:00:00.000"));
    assertThat(formatter.format(time.with(zonedDateTimerRoundedToNextOrSame(ChronoUnit.MINUTES, 60))),
            equalTo("2014-10-25 14:00:00.000"));

    assertThat(formatter.format(time.with(zonedDateTimerRoundedToNextOrSame(ChronoUnit.HOURS, 1))),
            equalTo("2014-10-25 14:00:00.000"));
    assertThat(formatter.format(time.with(zonedDateTimerRoundedToNextOrSame(ChronoUnit.HOURS, 2))),
            equalTo("2014-10-25 14:00:00.000"));
    assertThat(formatter.format(time.with(zonedDateTimerRoundedToNextOrSame(ChronoUnit.HOURS, 3))),
            equalTo("2014-10-25 15:00:00.000"));
    assertThat(formatter.format(time.with(zonedDateTimerRoundedToNextOrSame(ChronoUnit.HOURS, 5))),
            equalTo("2014-10-25 15:00:00.000"));
    assertThat(formatter.format(time.with(zonedDateTimerRoundedToNextOrSame(ChronoUnit.HOURS, 6))),
            equalTo("2014-10-25 18:00:00.000"));
    assertThat(formatter.format(time.with(zonedDateTimerRoundedToNextOrSame(ChronoUnit.HOURS, 12))),
            equalTo("2014-10-26 00:00:00.000"));

    // Truncating side-effect of rounding by 0
    assertThat(formatter.format(time.with(zonedDateTimerRoundedToNextOrSame(ChronoUnit.DAYS, 0))),
            equalTo("2014-10-25 00:00:00.000"));

    assertThat(formatter.format(time.with(zonedDateTimerRoundedToNextOrSame(ChronoUnit.DAYS, 1))),
            equalTo("2014-10-26 00:00:00.000"));
    // Every 'other' day counts from 1, i.e. 1, 3, .., 27
    assertThat(formatter.format(time.with(zonedDateTimerRoundedToNextOrSame(ChronoUnit.DAYS, 2))),
            equalTo("2014-10-27 00:00:00.000"));
    // Treat "7 days" as "next Monday"
    assertThat(formatter.format(time.with(zonedDateTimerRoundedToNextOrSame(ChronoUnit.DAYS, 7))),
            equalTo("2014-10-27 00:00:00.000"));
    assertThat(time.with(zonedDateTimerRoundedToNextOrSame(ChronoUnit.DAYS, 7)).getDayOfWeek(),
            equalTo(DayOfWeek.MONDAY));

    assertThat(formatter.format(time.with(zonedDateTimerRoundedToNextOrSame(ChronoUnit.MONTHS, 1))),
            equalTo("2014-11-01 00:00:00.000"));
    // Months counted from 1, so rounding by 2 gives 1, 3, ..9, 11
    assertThat(formatter.format(time.with(zonedDateTimerRoundedToNextOrSame(ChronoUnit.MONTHS, 2))),
            equalTo("2014-11-01 00:00:00.000"));
    assertThat(formatter.format(time.with(zonedDateTimerRoundedToNextOrSame(ChronoUnit.MONTHS, 6))),
            equalTo("2015-01-01 00:00:00.000"));

    assertThat(formatter.format(time.with(zonedDateTimerRoundedToNextOrSame(ChronoUnit.YEARS, 1))),
            equalTo("2015-01-01 00:00:00.000"));
    assertThat(formatter.format(time.with(zonedDateTimerRoundedToNextOrSame(ChronoUnit.YEARS, 2))),
            equalTo("2016-01-01 00:00:00.000"));
}
 
Example 19
Source File: Json.java    From morpheus-core with Apache License 2.0 2 votes vote down vote up
/**
 * Constructor
 * @param pattern   the format patterm
 */
public LocalTimeSerializer(String pattern) {
    this(DateTimeFormatter.ofPattern(pattern));
}
 
Example 20
Source File: Json.java    From morpheus-core with Apache License 2.0 2 votes vote down vote up
/**
 * Constructor
 * @param pattern   the format patterm
 */
public ZonedDateTimeSerializer(String pattern) {
    this(DateTimeFormatter.ofPattern(pattern));
}