Java Code Examples for java.time.format.DateTimeFormatter

The following are top voted examples for showing how to use java.time.format.DateTimeFormatter. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: openjdk-jdk10   File: HelloClasslist.java   Source Code and License 7 votes vote down vote up
public static void main(String ... args) {

        List<String> strings = Arrays.asList("Hello", "World!", "From: ",
              InetAddress.getLoopbackAddress().toString());

        String helloWorld = strings.parallelStream()
              .map(s -> s.toLowerCase(Locale.ROOT))
              .collect(joining(","));

        Stream.of(helloWorld.split(","))
              .forEach(System.out::println);

        String newDate = DateTimeFormatter.ISO_LOCAL_DATE_TIME.format(
                LocalDateTime.now(ZoneId.of("GMT")));

        String oldDate = String.format("%s%n",
                DateFormat.getDateInstance(DateFormat.DEFAULT, Locale.ROOT)
                        .format(new Date()));

        LOGGER.log(Level.INFO, "New Date: " + newDate + " - old: " + oldDate);
    }
 
Example 2
Project: lams   File: DateTimeFormatterRegistrar.java   Source Code and License 7 votes vote down vote up
@Override
public void registerFormatters(FormatterRegistry registry) {
	DateTimeConverters.registerConverters(registry);

	DateTimeFormatter dateFormatter = getFormatter(Type.DATE);
	DateTimeFormatter timeFormatter = getFormatter(Type.TIME);
	DateTimeFormatter dateTimeFormatter = getFormatter(Type.DATE_TIME);

	registry.addFormatterForFieldType(LocalDate.class,
			new TemporalAccessorPrinter(dateFormatter),
			new TemporalAccessorParser(LocalDate.class, dateFormatter));

	registry.addFormatterForFieldType(LocalTime.class,
			new TemporalAccessorPrinter(timeFormatter),
			new TemporalAccessorParser(LocalTime.class, timeFormatter));

	registry.addFormatterForFieldType(LocalDateTime.class,
			new TemporalAccessorPrinter(dateTimeFormatter),
			new TemporalAccessorParser(LocalDateTime.class, dateTimeFormatter));

	registry.addFormatterForFieldType(ZonedDateTime.class,
			new TemporalAccessorPrinter(dateTimeFormatter),
			new TemporalAccessorParser(ZonedDateTime.class, dateTimeFormatter));

	registry.addFormatterForFieldType(OffsetDateTime.class,
			new TemporalAccessorPrinter(dateTimeFormatter),
			new TemporalAccessorParser(OffsetDateTime.class, dateTimeFormatter));

	registry.addFormatterForFieldType(OffsetTime.class,
			new TemporalAccessorPrinter(timeFormatter),
			new TemporalAccessorParser(OffsetTime.class, timeFormatter));

	registry.addFormatterForFieldType(Instant.class, new InstantFormatter());

	registry.addFormatterForFieldAnnotation(new Jsr310DateTimeFormatAnnotationFormatterFactory());
}
 
Example 3
Project: Neukoelln_SER316   File: DefectLogManager.java   Source Code and License 6 votes vote down vote up
public static DefectLog createDefectLog(LocalDateTime date, int number, PSP.Defect type, PSP.Phase inject, PSP.Phase remove, int fixMin, int reference, String description) {
  refresh();
	Element element = new Element(DefectLog.ELEMENT_NAME);
	DateTimeFormatter formatter = DateTimeFormatter.ofPattern(DefectLog.DATE_FORMAT);
	element.addAttribute(new Attribute(DefectLog.ID_ELEMENT, Util.generateId()));
	element.addAttribute(new Attribute(DefectLog.DATE_ELEMENT, date.format(formatter)));
	element.addAttribute(new Attribute(DefectLog.NUMBER_ELEMENT, String.valueOf(number)));
	element.addAttribute(new Attribute(DefectLog.TYPE_ELEMENT, type.toString()));
	element.addAttribute(new Attribute(DefectLog.INJECT_ELEMENT, inject.toString()));
	element.addAttribute(new Attribute(DefectLog.REMOVE_ELEMENT, remove.toString()));
	element.addAttribute(new Attribute(DefectLog.FIX_ELEMENT, String.valueOf(fixMin)));
	element.addAttribute(new Attribute(DefectLog.REFERENCE_ELEMENT, String.valueOf(reference)));
	element.addAttribute(new Attribute(DefectLog.DESCRIPTION_ELEMENT, description));
	element.appendChild(description);
	Day d = getDay(date);
	
	if (d == null)
		d = createDay(date);
	
	d.getElement().appendChild(element);
	return new DefectLog(element);
}
 
Example 4
Project: cactoos   File: DateOfTest.java   Source Code and License 6 votes vote down vote up
@Test
public final void testParsingCustomFormatterStringToDate() {
    MatcherAssert.assertThat(
        "Can't parse a Date with custom format.",
        new DateOf(
            "2017-12-13 14:15:16.000000017",
            DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.n")
        ).value(),
        Matchers.is(
            Date.from(
                LocalDateTime.of(
                    2017, 12, 13, 14, 15, 16, 17
                ).toInstant(ZoneOffset.UTC)
            )
        )
    );
}
 
Example 5
Project: Neukoelln_SER316   File: TimeLogTest.java   Source Code and License 6 votes vote down vote up
@Test
public void testSetters() throws Exception {
	String timeValue = "2000-12-01 12:55";
	DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm");
	LocalDateTime timeStart = LocalDateTime.parse(timeValue, formatter);
	LocalDateTime timeStop = timeStart.plusMinutes(90);
	PSP.Phase phase = PSP.Phase.PostMortem;
	int interruption = 30;
	String comments = "this is a test";
	testLog.setTimeStart(timeStart);
	testLog.setTimeStop(timeStop);
	testLog.setInterruptionMin(interruption);
	testLog.setPhase(phase);
	testLog.setComments(comments);
	Assert.assertEquals(timeStart, testLog.getTimeStart());
	Assert.assertEquals(timeStop, testLog.getTimeStop());
	Assert.assertEquals(interruption, testLog.getInterruptionMin());
	Assert.assertEquals(phase, testLog.getPhase());
	Assert.assertEquals(comments, testLog.getComments());
}
 
Example 6
Project: device-bluetooth   File: ScheduleContext.java   Source Code and License 6 votes vote down vote up
private ZonedDateTime parseTime(String time) {
  // TODO : may support more than one format at some point
  DateTimeFormatter dtf = DateTimeFormatter.ofPattern(Schedule.DATETIME_FORMATS[0])
      .withZone(ZoneId.systemDefault());
  ZonedDateTime zdt = null;

  try {
    zdt = ZonedDateTime.parse(time, dtf);
  } catch (DateTimeParseException e) {
    logger.debug("parseTime() failed to parse '" + time + "'");
    // throw an exception
    // mark as complete (via max iterations?)
  }

  return zdt;
}
 
Example 7
Project: MoMuOSB   File: InfoCommands.java   Source Code and License 6 votes vote down vote up
/**
 * Help Command
 *
 * @param event MessageEvent
 * @param args  Argumente [Not needed]
 * @return state
 */
@Command(
        command = "getregister",
        description = "Display the help",
        alias = "greg",
        arguments = {"Mention User []"},
        permission = Globals.BOT_INFO,
        prefix = Globals.INFO_PREFIX
)
public boolean getRegisterDate(MessageReceivedEvent event, String[] args) {
    new Thread(() -> {
        StringBuilder content = new StringBuilder();
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd.MM.yyyy H:m:s");
        if (event.getMessage().getMentions().size() > 0) {
            for (IUser user : event.getMessage().getMentions()) {
                content.append(user.getName()).append(":  ").append(user.getCreationDate().format(formatter)).append("\n");
            }
        } else {
            content.append("No User specified");
        }
        BotUtils.sendMessage(event.getChannel(), content.toString(), false);
    }).start();
    return true;
}
 
Example 8
Project: winter   File: SortedNeighbourhoodBlockerTest.java   Source Code and License 6 votes vote down vote up
private DataSet<Movie, Attribute> generateDS1() {
	DataSet<Movie, Attribute> ds = new HashedDataSet<>();
	DateTimeFormatter formatter = new DateTimeFormatterBuilder()
	        .appendPattern("yyyy-MM-dd")
	        .parseDefaulting(ChronoField.CLOCK_HOUR_OF_DAY, 0)
	        .parseDefaulting(ChronoField.MINUTE_OF_HOUR, 0)
	        .parseDefaulting(ChronoField.SECOND_OF_MINUTE, 0)
	        .toFormatter(Locale.ENGLISH);
	
	Movie m1 = new Movie("1", "DS1");
	m1.setDate(LocalDateTime.parse("1980-10-10", formatter));
	ds.add(m1);
	Movie m2 = new Movie("2", "DS1");
	m2.setDate(LocalDateTime.parse("1990-10-10", formatter));
	ds.add(m2);
	Movie m3 = new Movie("3", "DS1");
	m3.setDate(LocalDateTime.parse("1991-10-10", formatter));
	ds.add(m3);
	return ds;
}
 
Example 9
Project: charts   File: StreamChart.java   Source Code and License 6 votes vote down vote up
private void redraw() {
    ctx.clearRect(0, 0, width, height);
    paths.forEach((path, plotItem) -> path.draw(ctx, true, true));
    Color             textColor      = getTextColor();
    int               noOfCategories = chartItems.size();
    DateTimeFormatter formatter      = getCategory().formatter();

    for (int category = 0 ; category < noOfCategories ; category++) {
        List<ChartItemData> itemDataInCategory = itemsPerCategory.get(category);

        // Go through all item data of the current category
        for (ChartItemData itemData : itemDataInCategory) {
            ChartItem item      = itemData.getChartItem();
            CtxBounds bounds    = itemData.getBounds();
            Color     itemColor = item.getFill();

            // Draw item boxes with their labels
            ctx.setFill(itemColor);
            ctx.fillRect(bounds.getX(), bounds.getY(), bounds.getWidth(), bounds.getHeight());
            ctx.setLineWidth(0);
            ctx.setStroke(itemColor);
            ctx.strokeRect(bounds.getX(), bounds.getY(), bounds.getWidth(), bounds.getHeight());

            if (item.getValue() > 1) {
                ctx.setFill(textColor);
                ctx.setTextAlign(category == noOfCategories ? TextAlignment.RIGHT : TextAlignment.LEFT);
                ctx.fillText(item.getName(), itemData.getTextPoint().getX(), itemData.getTextPoint().getY(), bounds.getWidth());
            }
        }
        // Draw category text
        ChartItemData firstItem = itemDataInCategory.get(0);
        ctx.fillText(formatter.format(firstItem.getLocalDate()), firstItem.getTextPoint().getX(), reducedHeight + size * 0.02, firstItem.bounds.getWidth());
    }
}
 
Example 10
Project: Saber-Bot   File: SkipCommand.java   Source Code and License 6 votes vote down vote up
@Override
public void action(String prefix, String[] args, MessageReceivedEvent event)
{
    int index = 0;
    Integer entryId = ParsingUtilities.encodeIDToInt(args[index++]);
    ScheduleEntry se = Main.getEntryManager().getEntryFromGuild(entryId, event.getGuild().getId());

    // send a confirmation to the channel
    String content;
    if(se.getRecurrence().shouldRepeat(se.getStart()))
    {
        se.repeat();
        content = "The event has been cancelled.\n" +
                "The event is next scheduled for " +
                se.getStart().format(DateTimeFormatter.ofPattern("MMM d, hh:mm a"));
    }
    else
    {
        se.repeat();
        content = "The event has been cancelled.";
    }
    MessageUtilities.sendMsg(content, event.getTextChannel(), null);
}
 
Example 11
Project: JavaHomework   File: PIMTodo.java   Source Code and License 6 votes vote down vote up
public static PIMTodo FromString(String s)
{
    //s likes "Type: PIMTodo    Priority: normal    Date: 2017-04-20    text""
    String[] ss = s.split("(Type: )|(Priority: )|(Date: )|(    )");
    String[] sss = new String[4];
    int temp = 0;
    for (String var : ss) {
        if(temp >= 4){
            System.out.println("Input String can't to PIMTodo.");
            return null;
        }
        if(!var.equals("")){
            sss[temp] = var;
            temp ++;
        }
    }
    if(!sss[0].equals("PIMTodo")){
        System.out.println("Input String can't to PIMTodo.");
        return null;
    }

    return new PIMTodo(sss[3], LocalDate.parse(sss[2],DateTimeFormatter.ofPattern("yyyy-MM-dd")), sss[1]);
}
 
Example 12
Project: OperatieBRP   File: AbstractZoekPersoonOphalenPersoonServiceImpl.java   Source Code and License 6 votes vote down vote up
@Bedrijfsregel(Regel.R2402)
private List<Long> bepaalPersoonIds(final Set<ZoekCriterium> zoekCriteria, final Integer maxAantalZoekResultaten,
                                    final ZoekPersoonGeneriekVerzoek.ZoekBereikParameters zoekBereikParameters)
        throws StapMeldingException, QueryNietUitgevoerdException {
    final List<Long> persoonIds;
    final boolean historisch = zoekBereikParameters != null && (zoekBereikParameters.getPeilmomentMaterieel() != null || Zoekbereik.MATERIELE_PERIODE
            .equals(zoekBereikParameters.getZoekBereik()));
    if (historisch) {
        Integer peilmomentMaterieel = null;
        if (zoekBereikParameters.getPeilmomentMaterieel() != null) {
            peilmomentMaterieel = Integer.parseInt(
                    datumService.parseDate(zoekBereikParameters.getPeilmomentMaterieel()).format(DateTimeFormatter.BASIC_ISO_DATE));
        }
        persoonIds = zoekPersoonDataOphalerService
                .zoekPersonenHistorisch(zoekCriteria, peilmomentMaterieel,
                        Zoekbereik.MATERIELE_PERIODE.equals(zoekBereikParameters.getZoekBereik()), maxAantalZoekResultaten);
    } else {
        persoonIds = zoekPersoonDataOphalerService.zoekPersonenActueel(zoekCriteria, maxAantalZoekResultaten);
    }
    return persoonIds;
}
 
Example 13
Project: device-opcua-java   File: ScheduleContext.java   Source Code and License 6 votes vote down vote up
private ZonedDateTime parseTime(String time) {
  // TODO : may support more than one format at some point
  DateTimeFormatter dtf =
      DateTimeFormatter.ofPattern(Schedule.DATETIME_FORMATS[0]).withZone(ZoneId.systemDefault());
  ZonedDateTime zdt = null;

  try {
    zdt = ZonedDateTime.parse(time, dtf);
  } catch (DateTimeParseException e) {
    logger.debug("parseTime() failed to parse '" + time + "'");
    // throw an exception
    // mark as complete (via max iterations?)
  }

  return zdt;
}
 
Example 14
Project: jdk8u-jdk   File: TCKDateTimeParseResolver.java   Source Code and License 5 votes vote down vote up
@Test(dataProvider="resolveThreeToDate")
public void test_resolveThreeToDate(TemporalField field1, long value1,
                                  TemporalField field2, long value2,
                                  TemporalField field3, long value3,
                                  LocalDate expectedDate) {
    String str = value1 + " " + value2 + " " + value3;
    DateTimeFormatter f = new DateTimeFormatterBuilder()
            .appendValue(field1).appendLiteral(' ')
            .appendValue(field2).appendLiteral(' ')
            .appendValue(field3).toFormatter();

    TemporalAccessor accessor = f.parse(str);
    assertEquals(accessor.query(TemporalQueries.localDate()), expectedDate);
    assertEquals(accessor.query(TemporalQueries.localTime()), null);
}
 
Example 15
Project: openjdk-jdk10   File: TCKDateTimeFormatter.java   Source Code and License 5 votes vote down vote up
@Test(expectedExceptions=DateTimeParseException.class)
public void test_parse_CharSequence_ParsePosition_parseError() {
    DateTimeFormatter test = DateTimeFormatter.ISO_DATE;
    ParsePosition pos = new ParsePosition(3);
    try {
        test.parse("XXX2012XXX", pos);
        fail();
    } catch (DateTimeParseException ex) {
        assertEquals(ex.getErrorIndex(), 7);
        throw ex;
    }
}
 
Example 16
Project: Saber-Bot   File: Logging.java   Source Code and License 5 votes vote down vote up
/**
 * used logging minor (possibly expected) errors (level 2)
 * @param caller the java class from which the command is called
 * @param msg the message to log
 */
public static void warn(Class caller, String msg)
{
    if(Main.getBotSettingsManager().getLogLevel() < 2) return;

    String now = LocalTime.now().truncatedTo(ChronoUnit.SECONDS).format(DateTimeFormatter.ISO_LOCAL_TIME);
    String content = "[" + now + "] " +
            ANSI_RED + "[Warn]" + ANSI_RESET + " " +
            ANSI_YELLOW_BACKGROUND + ANSI_BLACK +
            "[" + caller.getSimpleName() + "]" +
            ANSI_RESET + " " + ANSI_RED + msg +
            ANSI_RESET;

    System.out.println(content);
}
 
Example 17
Project: swallow-core   File: DateUtils.java   Source Code and License 5 votes vote down vote up
/**
 * 格式化日期
 *
 * @param localDateTime 日期
 * @param pattern       日期格式
 * @return 格式化后的日期字符串
 */
public static String format(LocalDateTime localDateTime, String pattern) {
    Objects.requireNonNull(localDateTime, "localDateTime is null.");
    try {
        return localDateTime.format(DateTimeFormatter.ofPattern(pattern));
    } catch (Exception e) {
        throw new SwallowException("pattern is incorrect.", e);
    }
}
 
Example 18
Project: java-velocypack-module-jdk8   File: VPackTimeTest.java   Source Code and License 5 votes vote down vote up
@Test
public void offsetDateTimeCompatibilityWithDateTimeFormatter() throws Exception {
	final OffsetDateTime out = OffsetDateTime.now();
	final String s = out.format(DateTimeFormatter.ISO_OFFSET_DATE_TIME);
	final OffsetDateTime in = VPackJdk8Deserializers.OFFSET_DATE_TIME.deserialize(null,
		new VPackBuilder().add(s).slice(), null);
	assertThat(in, is(out));
}
 
Example 19
Project: openjdk-jdk10   File: TCKDateTimeFormatters.java   Source Code and License 5 votes vote down vote up
@Test(dataProvider="sample_isoOffsetDate")
public void test_parse_isoOffsetDate(
        Integer year, Integer month, Integer day, String offsetId, String zoneId,
        String input, Class<?> invalid) {
    if (input != null) {
        Expected expected = createDate(year, month, day);
        buildCalendrical(expected, offsetId, null);  // zone not expected to be parsed
        assertParseMatch(DateTimeFormatter.ISO_OFFSET_DATE.parseUnresolved(input, new ParsePosition(0)), expected);
    }
}
 
Example 20
Project: jdk8u-jdk   File: TCKDateTimeParseResolver.java   Source Code and License 5 votes vote down vote up
@Test
public void test_fieldResolvesToChronoLocalDateTime_overrideChrono_matches() {
    MinguoDate mdt = MinguoDate.of(100, 6, 30);
    DateTimeFormatter f = new DateTimeFormatterBuilder().appendValue(new ResolvingField(mdt.atTime(LocalTime.NOON))).toFormatter();
    f = f.withChronology(MinguoChronology.INSTANCE);
    TemporalAccessor accessor = f.parse("1234567890");
    assertEquals(accessor.query(TemporalQueries.localDate()), LocalDate.from(mdt));
    assertEquals(accessor.query(TemporalQueries.localTime()), LocalTime.NOON);
    assertEquals(accessor.query(TemporalQueries.chronology()), MinguoChronology.INSTANCE);
}
 
Example 21
Project: jdk8u-jdk   File: TCKIsoFields.java   Source Code and License 5 votes vote down vote up
@Test(dataProvider="week")
public void test_parse_weeks_SMART(LocalDate date, DayOfWeek dow, int week, int wby) {
    DateTimeFormatter f = new DateTimeFormatterBuilder()
            .appendValue(IsoFields.WEEK_BASED_YEAR).appendLiteral('-')
            .appendValue(IsoFields.WEEK_OF_WEEK_BASED_YEAR).appendLiteral('-')
            .appendValue(DAY_OF_WEEK)
            .toFormatter().withResolverStyle(ResolverStyle.SMART);
    LocalDate parsed = LocalDate.parse(wby + "-" + week + "-" + dow.getValue(), f);
    assertEquals(parsed, date);
}
 
Example 22
Project: wall-t   File: TileView.java   Source Code and License 5 votes vote down vote up
private HBox createLastBuildInfoBox( final TileViewModel build ) {
    final HBox lastBuildInfoPart = new HBox( );
    lastBuildInfoPart.setAlignment( Pos.CENTER );

    final ImageView lastBuildIcon = new ImageView( UIUtils.createImage( "icons/lastBuild.png" ) );
    lastBuildIcon.setPreserveRatio( true );
    lastBuildIcon.setFitWidth( 32 );

    final Label lastBuildDate = new Label( );
    lastBuildDate.setMinWidth( 110 );
    lastBuildDate.setTextAlignment( CENTER );
    lastBuildDate.setAlignment( Pos.CENTER );
    lastBuildDate.setFont( UIUtils.font( 32, FontWeight.BOLD ) );
    lastBuildDate.setTextFill( Color.WHITE );
    lastBuildDate.setWrapText( true );
    lastBuildDate.setLineSpacing( 2 );  // TODO: Seems do not work
    lastBuildDate.setEffect( UIUtils.shadowEffect( ) );
    lastBuildDate.textProperty( ).bind( createStringBinding( ( ) -> {
        final LocalDateTime localDateTime = build.lastFinishedDateProperty( ).get( );
        if ( localDateTime == null )
            return "00/00\n00:00";
        return localDateTime.format( DateTimeFormatter.ofPattern( "dd/MM\nHH:mm" ) );
    }, build.lastFinishedDateProperty( ) ) );

    lastBuildInfoPart.getChildren( ).addAll( lastBuildIcon, lastBuildDate );
    return lastBuildInfoPart;
}
 
Example 23
Project: openjdk-jdk10   File: TestDateTimeFormatterBuilder.java   Source Code and License 5 votes vote down vote up
@Test(dataProvider="offsetPatterns")
public void test_appendOffset_format(String pattern, int h, int m, int s, String expected) throws Exception {
    builder.appendOffset(pattern, "Z");
    DateTimeFormatter f = builder.toFormatter();
    ZoneOffset offset = ZoneOffset.ofHoursMinutesSeconds(h, m, s);
    assertEquals(f.format(offset), expected);
}
 
Example 24
Project: jdk8u-jdk   File: TCKDateTimeParseResolver.java   Source Code and License 5 votes vote down vote up
@Test
public void test_withChronology_parsedChronology_noOverride() {
    DateTimeFormatter f = new DateTimeFormatterBuilder().parseDefaulting(EPOCH_DAY, 2).appendChronologyId().toFormatter();
    TemporalAccessor accessor = f.parse("ThaiBuddhist");
    assertEquals(accessor.query(TemporalQueries.localDate()), LocalDate.of(1970, 1, 3));
    assertEquals(accessor.query(TemporalQueries.localTime()), null);
    assertEquals(accessor.query(TemporalQueries.chronology()), ThaiBuddhistChronology.INSTANCE);
}
 
Example 25
Project: openjdk-jdk10   File: TCKDateTimeFormatters.java   Source Code and License 5 votes vote down vote up
@Test(dataProvider="sample_isoInstant")
public void test_parse_isoInstant(
        long instantSecs, Integer nano, String input, Class<?> invalid) {
    if (input != null) {
        TemporalAccessor parsed = DateTimeFormatter.ISO_INSTANT.parseUnresolved(input, new ParsePosition(0));
        assertEquals(parsed.getLong(INSTANT_SECONDS), instantSecs);
        assertEquals(parsed.getLong(NANO_OF_SECOND), (nano == null ? 0 : nano));
    }
}
 
Example 26
Project: apollo-custom   File: ServiceExceptionTest.java   Source Code and License 5 votes vote down vote up
@Test
public void testAdminServiceException() {
	String errorMsg = "No available admin service";
	String errorCode = "errorCode";
	String status = "500";

	Map<String, Object> errorAttributes = new LinkedHashMap<>();
	errorAttributes.put("status", status);
	errorAttributes.put("message", errorMsg);
	errorAttributes.put("timestamp",
											LocalDateTime.now().format(DateTimeFormatter.ISO_LOCAL_DATE_TIME));
	errorAttributes.put("exception", ServiceException.class.getName());
	errorAttributes.put("errorCode", errorCode);

	HttpStatusCodeException adminException =
			new HttpServerErrorException(HttpStatus.INTERNAL_SERVER_ERROR, "admin server error",
																	 new Gson().toJson(errorAttributes).getBytes(), Charset.defaultCharset());

	when(appService.createAppInLocal(any())).thenThrow(adminException);

	AppModel app = generateSampleApp();
	try {
		appController.create(app);
	} catch (HttpStatusCodeException e) {
		@SuppressWarnings("unchecked")
		Map<String, String> attr = new Gson().fromJson(e.getResponseBodyAsString(), Map.class);
		Assert.assertEquals(errorMsg, attr.get("message"));
		Assert.assertEquals(errorCode, attr.get("errorCode"));
		Assert.assertEquals(status, attr.get("status"));
	}
}
 
Example 27
Project: openjdk-jdk10   File: TCKDateTimeParseResolver.java   Source Code and License 5 votes vote down vote up
@Test(dataProvider="resolveOneToTime")
public void test_resolveOneToTime(TemporalField field1, long value1, LocalTime expectedTime) {
    String str = Long.toString(value1);
    DateTimeFormatter f = new DateTimeFormatterBuilder().appendValue(field1).toFormatter();

    TemporalAccessor accessor = f.parse(str);
    assertEquals(accessor.query(TemporalQueries.localDate()), null);
    assertEquals(accessor.query(TemporalQueries.localTime()), expectedTime);
}
 
Example 28
Project: GitHub   File: Issue1493.java   Source Code and License 5 votes vote down vote up
public void test_for_issue() throws Exception {

        TestBean test = new TestBean();
        String stime2 = "2017-09-22 15:08:56";

        LocalDateTime time1 = LocalDateTime.now();
        time1 = time1.minusNanos(10L);
        System.out.println(time1.getNano());
        LocalDateTime time2 = LocalDateTime.parse(stime2, DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss", Locale.CHINA));
        test.setTime1(time1);
        test.setTime2(time2);
        String t1 = JSON.toJSONString(time1, SerializerFeature.WriteDateUseDateFormat);

        String json = JSON.toJSONString(test, SerializerFeature.WriteDateUseDateFormat);
        Assert.assertEquals("{\"time1\":"+t1+",\"time2\":\""+stime2+"\"}",json);


        //String default_format = JSON.DEFFAULT_LOCAL_DATE_TIME_FORMAT;
        //JSON.DEFFAULT_LOCAL_DATE_TIME_FORMAT = "yyyy-MM-dd HH:mm:ss";
        //String stime1 = DateTimeFormatter.ofPattern(JSON.DEFFAULT_LOCAL_DATE_TIME_FORMAT, Locale.CHINA).format(time1);

        json = JSON.toJSONString(test, SerializerFeature.WriteDateUseDateFormat);
        Assert.assertEquals("{\"time1\":"+ JSON.toJSONString(time1, SerializerFeature.WriteDateUseDateFormat) +",\"time2\":\""+stime2+"\"}",json);


        String pattern = "yyyy-MM-dd HH:mm:ss";
        String stime1 = DateTimeFormatter.ofPattern(pattern, Locale.CHINA).format(time1);

        json = JSON.toJSONStringWithDateFormat(test, "yyyy-MM-dd HH:mm:ss", SerializerFeature.WriteDateUseDateFormat);
        Assert.assertEquals("{\"time1\":\""+stime1+"\",\"time2\":\""+stime2+"\"}",json);

        //JSON.DEFFAULT_LOCAL_DATE_TIME_FORMAT = default_format;
    }
 
Example 29
Project: esup-ecandidat   File: MethodUtils.java   Source Code and License 5 votes vote down vote up
/**
 * @param date
 * @param formatterDate
 * @return la date formatee
 */
public static String formatDate(LocalDate date, DateTimeFormatter formatterDate) {
	if (date == null) {
		return "";
	} else {
		return date.format(formatterDate);
	}
}
 
Example 30
Project: xm-ms-entity   File: MappingUtils.java   Source Code and License 5 votes vote down vote up
public static String format(Instant instant, String pattern) {
    if (instant != null) {
        try {
            return DateTimeFormatter.ofPattern(pattern).withZone(ZoneId.systemDefault()).format(instant);
        } catch (DateTimeException | IllegalArgumentException e) {
            log.error("Wrong instant: {} or pattern: {}", instant, pattern, e);
            return null;
        }
    }
    return null;
}
 
Example 31
Project: openjdk-jdk10   File: TCKDateTimeFormatter.java   Source Code and License 5 votes vote down vote up
@Test
public void test_resolverFields_listOfOneNull() throws Exception {
    DateTimeFormatter f = new DateTimeFormatterBuilder()
            .appendValue(YEAR).toFormatter().withResolverFields((TemporalField) null);
    TemporalAccessor parsed = f.parse("2012");
    assertEquals(parsed.isSupported(YEAR), false);  // not in the list of resolverFields
}
 
Example 32
Project: jdk8u-jdk   File: TCKDateTimeFormatter.java   Source Code and License 5 votes vote down vote up
@Test
public void test_toFormat_parseObject_StringParsePosition() throws Exception {
    DateTimeFormatter test = fmt.withLocale(Locale.ENGLISH).withDecimalStyle(DecimalStyle.STANDARD);
    Format format = test.toFormat();
    ParsePosition pos = new ParsePosition(0);
    TemporalAccessor result = (TemporalAccessor) format.parseObject("ONE30XXX", pos);
    assertEquals(pos.getIndex(), 5);
    assertEquals(pos.getErrorIndex(), -1);
    assertEquals(result.isSupported(DAY_OF_MONTH), true);
    assertEquals(result.getLong(DAY_OF_MONTH), 30L);
}
 
Example 33
Project: tipi-engine   File: Activity.java   Source Code and License 5 votes vote down vote up
protected LocalDate getLocalDateVariable(String name) {
    Integer i = (Integer) facade.getVariable(name);
    if (i != null) {
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyMMdd");
        formatter = formatter.withLocale(Locale.FRENCH);
        LocalDate date = LocalDate.parse("" + i, formatter);
        return date;
    }
    return null;
}
 
Example 34
Project: qpp-conversion-tool   File: JsonWrapper.java   Source Code and License 5 votes vote down vote up
/**
 * Validates that the given value conforms to expected date formatting (i.e. yyyyMMdd).
 *
 * @param value to validate
 * @return valid date String
 * @throws EncodeException
 */
protected String validDate(String value) {
	try {
		LocalDate thisDate = LocalDate.parse(cleanString(value),  DateTimeFormatter.ofPattern("yyyyMMdd"));
		return thisDate.format(DateTimeFormatter.ofPattern("yyyy-MM-dd"));
	} catch (Exception e) {
		throw new EncodeException(value + " is not an date of format YYYYMMDD.", e);
	}
}
 
Example 35
Project: jdk8u-jdk   File: TCKDateTimeFormatter.java   Source Code and License 5 votes vote down vote up
@Test
public void test_resolverFields_ignoreCrossCheck() throws Exception {
    DateTimeFormatter base = new DateTimeFormatterBuilder()
            .appendValue(YEAR).appendLiteral('-').appendValue(DAY_OF_YEAR).appendLiteral('-')
            .appendValue(DAY_OF_WEEK).toFormatter();
    DateTimeFormatter f = base.withResolverFields(YEAR, DAY_OF_YEAR);
    try {
        base.parse("2012-321-1", LocalDate::from);  // wrong day-of-week
        fail();
    } catch (DateTimeException ex) {
        // expected, should fail in cross-check of day-of-week
    }
    LocalDate parsed = f.parse("2012-321-1", LocalDate::from);  // ignored wrong day-of-week
    assertEquals(parsed, LocalDate.of(2012, 11, 16));
}
 
Example 36
Project: openjdk-jdk10   File: TestDateTimeFormatterBuilder.java   Source Code and License 5 votes vote down vote up
@Test(dataProvider="offsetPatterns")
public void test_appendOffset_parse(String pattern, int h, int m, int s, String expected) throws Exception {
    builder.appendOffset(pattern, "Z");
    DateTimeFormatter f = builder.toFormatter();
    ZoneOffset offset = ZoneOffset.ofHoursMinutesSeconds(h, m, s);
    ZoneOffset parsed = f.parse(expected, ZoneOffset::from);
    assertEquals(f.format(parsed), expected);
}
 
Example 37
Project: JSK   File: JSKDateConverter.java   Source Code and License 5 votes vote down vote up
/**
 * This method returns as {@link String} the {@link LocalDateTime} passed as parameter using a {@link DateTimeFormatter}.
 * @param date {@link LocalDateTime}
 * @param formatter {@link DateTimeFormatter}
 * @return {@link String}
 * @throws JSKException if some of the parameters are null.
 */
public static String dateToString(LocalDateTime date, DateTimeFormatter formatter) throws JSKException {
	
	if (isNull(date, formatter)) {
           throw new JSKException(NULL_PARAMETERS);
       }
	
	return date.format(formatter);
}
 
Example 38
Project: jdk8u-jdk   File: TCKDateTimeFormatter.java   Source Code and License 5 votes vote down vote up
@Test
public void test_toFormat_parseObject_String() throws Exception {
    DateTimeFormatter test = fmt.withLocale(Locale.ENGLISH).withDecimalStyle(DecimalStyle.STANDARD);
    Format format = test.toFormat();
    TemporalAccessor result = (TemporalAccessor) format.parseObject("ONE30");
    assertEquals(result.isSupported(DAY_OF_MONTH), true);
    assertEquals(result.getLong(DAY_OF_MONTH), 30L);
}
 
Example 39
Project: oo-systems-development   File: TicketSystem.java   Source Code and License 5 votes vote down vote up
/**Method that allows other methods to find a particular show
* @param eventName The name of the event that is being looked for
* @param showStart The date and time of the start of the show
* in the dd.MM.yyyy HH:mm format
* @return A reference to the show object that is being worked on
*/
public Show findShow(String eventName, String showStart)
{
  if(findEvent(eventName) != null)
  {
    DateTimeFormatter format = DateTimeFormatter.ofPattern("dd.MM.yyyy HH:mm");
    LocalDateTime startDate = LocalDateTime.parse(showStart, format);
    Show show = findEvent(eventName).getShow(startDate);
    return show;
  }
  else
  {
      return null;
  }
}
 
Example 40
Project: jdk8u-jdk   File: TestDateTimeFormatterBuilder.java   Source Code and License 5 votes vote down vote up
@Test
public void test_appendValueReduced_subsequent_parse() throws Exception {
    builder.appendValue(MONTH_OF_YEAR, 1, 2, SignStyle.NORMAL).appendValueReduced(YEAR, 2, 2, 2000);
    DateTimeFormatter f = builder.toFormatter();
    assertEquals(f.toString(), "Value(MonthOfYear,1,2,NORMAL)ReducedValue(Year,2,2,2000)");
    ParsePosition ppos = new ParsePosition(0);
    TemporalAccessor parsed = f.parseUnresolved("123", ppos);
    assertNotNull(parsed, "Parse failed: " + ppos.toString());
    assertEquals(parsed.getLong(MONTH_OF_YEAR), 1L);
    assertEquals(parsed.getLong(YEAR), 2023L);
}