Example usage for java.time.format DateTimeFormatter ofPattern

List of usage examples for java.time.format DateTimeFormatter ofPattern

Introduction

In this page you can find the example usage for java.time.format DateTimeFormatter ofPattern.

Prototype

public static DateTimeFormatter ofPattern(String pattern) 

Source Link

Document

Creates a formatter using the specified pattern.

Usage

From source file:agendapoo.Model.Atividade.java

/**
 * LocalDate possui o formato da data seguindo esse modelo "yyyy-MM-dd", esse
 * mtodo tem como objetivo retornar a String da LocalDate com sua data
 * no formato "dd/MM/yyyy".//from  w w  w .  ja  v a  2  s .com
 * @return String contendo a data formatada no padro dd/MM/yyyy.
 */
public String getFormattedDate() {
    DateTimeFormatter dtf = DateTimeFormatter.ofPattern("dd/MM/yyyy");
    return this.data.format(dtf);
}

From source file:com.streamsets.pipeline.stage.processor.parser.TestDataParserProcessor.java

@Test
public void testSyslogParsing() throws Exception {
    int priority = 17;
    int facility = priority / 8;
    int severity = priority % 8;
    LocalDateTime date = LocalDateTime.now().withNano(0);
    String host = "1.2.3.4";
    String rest = "Nothing interesting happened.";

    String inputFieldPath = "input";
    String outputFieldPath = "/output";

    String syslogMsg = String.format("<%d>%s %s %s", priority,
            DateTimeFormatter.ofPattern("MMM dd HH:mm:ss").format(date), host, rest);

    DataParserConfig configs = new DataParserConfig();
    configs.dataFormat = DataFormat.SYSLOG;
    final DataParserFormatConfig dataParserFormatConfig = new DataParserFormatConfig();
    configs.dataFormatConfig = dataParserFormatConfig;
    configs.fieldPathToParse = "/" + inputFieldPath;
    configs.parsedFieldPath = outputFieldPath;

    DataParserProcessor processor = new DataParserProcessor(configs);

    final String outputLane = "out";

    ProcessorRunner runner = new ProcessorRunner.Builder(DataParserDProcessor.class, processor)
            .addOutputLane(outputLane).setOnRecordError(OnRecordError.TO_ERROR).build();
    Map<String, Field> map = new HashMap<>();
    map.put(inputFieldPath, Field.create(syslogMsg));
    Record record = RecordCreator.create();
    record.set(Field.create(map));
    List<Record> input = new ArrayList<>();
    input.add(record);//from w  w  w  . j av a 2  s .c o m
    try {
        runner.runInit();
        StageRunner.Output output = runner.runProcess(input);
        assertTrue(output.getRecords().containsKey(outputLane));
        final List<Record> records = output.getRecords().get(outputLane);
        assertEquals(1, records.size());
        assertTrue(records.get(0).has(outputFieldPath));
        assertEquals(Field.Type.MAP, records.get(0).get(outputFieldPath).getType());
        Map<String, Field> syslogFields = records.get(0).get(outputFieldPath).getValueAsMap();
        assertThat(syslogFields, hasKey(SyslogMessage.FIELD_SYSLOG_PRIORITY));
        assertThat(syslogFields.get(SyslogMessage.FIELD_SYSLOG_PRIORITY), fieldWithValue(priority));
        assertThat(syslogFields.get(SyslogMessage.FIELD_SYSLOG_FACILITY), fieldWithValue(facility));
        assertThat(syslogFields.get(SyslogMessage.FIELD_SYSLOG_SEVERITY), fieldWithValue(severity));
        assertThat(syslogFields.get(SyslogMessage.FIELD_HOST), fieldWithValue(host));
        assertThat(syslogFields.get(SyslogMessage.FIELD_REMAINING), fieldWithValue(rest));
        assertThat(syslogFields.get(SyslogMessage.FIELD_RAW), fieldWithValue(syslogMsg));
        assertThat(syslogFields.get(SyslogMessage.FIELD_TIMESTAMP),
                fieldWithValue(date.toInstant(ZoneOffset.UTC).toEpochMilli()));

    } finally {
        runner.runDestroy();
    }
}

From source file:de.rkl.tools.tzconv.configuration.ConfiguredComponentsProvider.java

@Bean(name = BEAN_NAME_DATE_TIME_FORMATTER)
public DateTimeFormatter configureDateTimeFormatter() {
    return DateTimeFormatter.ofPattern("VV: dd-MM-yyyy kk:mm");
}

From source file:dpfmanager.shell.interfaces.gui.component.report.ReportsController.java

private LocalDate parseFolderName(String folder) {
    try {// w  w  w.  j  a va  2s.co  m
        return LocalDate.parse(folder, DateTimeFormatter.ofPattern("yyyyMMdd"));
    } catch (Exception e) {
        return null;
    }
}

From source file:dijalmasilva.controllers.LugarController.java

@RequestMapping("/filtrar/data")
public String filtrarPorData(Date dataFiltro, HttpServletRequest req) {
    List<Lugar> todasOcorrencias = service.buscarPorData(dataFiltro.toLocalDate());
    req.getServletContext().setAttribute("todasOcorrencias", todasOcorrencias);
    req.setAttribute("result", "Ocorrncias ocorridas no dia "
            + dataFiltro.toLocalDate().format(DateTimeFormatter.ofPattern("dd/MM/yyyy")));
    req.getServletContext().setAttribute("existeFiltro", true);
    return "home";
}

From source file:com.actelion.research.spiritcore.services.SampleListValidator.java

public SampleListValidator() throws Exception {
    dtfBuilder.parseCaseInsensitive();//from   ww  w .  ja  v a2  s .  c om
    for (String pattern : dtPatterns)
        dtfBuilder.appendOptional(DateTimeFormatter.ofPattern(pattern));
}

From source file:scouterx.webapp.request.SummaryRequest.java

private void setTimeAsYmd() {
    ZoneId zoneId = ZoneId.systemDefault();
    DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyMMddHHmm");
    LocalDateTime startDateTime = LocalDateTime.parse(startYmdHm, formatter);
    LocalDateTime endDateTime = LocalDateTime.parse(endYmdHm, formatter);

    startTimeMillis = startDateTime.atZone(zoneId).toEpochSecond() * 1000L;
    endTimeMillis = endDateTime.atZone(zoneId).toEpochSecond() * 1000L;
}

From source file:com.publictransitanalytics.scoregenerator.output.PointAccessibility.java

public PointAccessibility(final int taskCount, final PathScoreCard scoreCard, final Grid grid,
        final PointLocation centerPoint, final LocalDateTime startTime, final LocalDateTime lastTime,
        final Duration samplingInterval, final Duration tripDuration, final boolean backward,
        final Duration inServiceTime) throws InterruptedException {
    type = AccessibilityType.POINT_ACCESSIBILITY;
    direction = backward ? Direction.INBOUND : Direction.OUTBOUND;
    mapBounds = new Bounds(grid.getBounds());
    center = new Point(centerPoint);
    this.startTime = startTime.format(DateTimeFormatter.ofPattern("YYYY-MM-dd HH:mm:ss"));
    this.endTime = lastTime.format(DateTimeFormatter.ofPattern("YYYY-MM-dd HH:mm:ss"));
    this.samplingInterval = DurationFormatUtils.formatDurationWords(samplingInterval.toMillis(), true, true);

    this.tripDuration = DurationFormatUtils.formatDurationWords(tripDuration.toMillis(), true, true);

    this.taskCount = taskCount;

    final Set<Sector> sectors = grid.getAllSectors();
    totalSectors = grid.getReachableSectors().size();

    final ImmutableMap.Builder<Bounds, SectorReachInformation> informationBuilder = ImmutableMap.builder();

    for (final Sector sector : sectors) {
        final Map<LogicalTask, MovementPath> taskPaths = scoreCard.getBestPaths(sector);
        if (!taskPaths.isEmpty()) {
            final ImmutableSet.Builder<MovementPath> bestPathsBuilder = ImmutableSet.builder();
            int count = 0;
            for (final MovementPath taskPath : taskPaths.values()) {
                if (taskPath != null) {
                    bestPathsBuilder.add(taskPath);
                    count++;//  www  . j  ava2 s  .  c om
                }
            }
            final Bounds bounds = new Bounds(sector);
            final Set<LocalDateTime> reachTimes = scoreCard.getReachedTimes(sector);
            final SectorReachInformation information = new SectorReachInformation(bestPathsBuilder.build(),
                    count, reachTimes);
            informationBuilder.put(bounds, information);
        }
    }
    sectorPaths = informationBuilder.build();

    inServiceSeconds = inServiceTime.getSeconds();
}

From source file:squash.booking.lambdas.GetBookingsLambdaTest.java

@Before
public void beforeTest() throws Exception {
    mockery = new Mockery();
    getBookingsLambda = new TestGetBookingsLambda();
    getBookingsLambda.setBookingManager(mockery.mock(IBookingManager.class));

    // Set up the valid date range
    List<String> validDates = new ArrayList<>();
    fakeCurrentDate = LocalDate.of(2015, 10, 6);
    fakeCurrentDateString = fakeCurrentDate.format(DateTimeFormatter.ofPattern("yyyy-MM-dd"));
    validDates.add(fakeCurrentDateString);
    validDates.add(fakeCurrentDate.plusDays(1).format(DateTimeFormatter.ofPattern("yyyy-MM-dd")));
    getBookingsLambda.setValidDates(validDates);

    // Set up mock context
    mockContext = mockery.mock(Context.class);
    mockery.checking(new Expectations() {
        {//from   w  ww .  j a  v  a 2  s .com
            ignoring(mockContext);
        }
    });

    // Set up mock logger
    mockLogger = mockery.mock(LambdaLogger.class);
    mockery.checking(new Expectations() {
        {
            ignoring(mockLogger);
        }
    });

    // Set up mock lifecycle manager
    mockLifecycleManager = mockery.mock(ILifecycleManager.class);
    mockery.checking(new Expectations() {
        {
            allowing(mockLifecycleManager).getLifecycleState();
            will(returnValue(new ImmutablePair<LifecycleState, Optional<String>>(LifecycleState.ACTIVE,
                    Optional.empty())));
        }
    });
    getBookingsLambda.setLifecycleManager(mockLifecycleManager);

    // Set up some typical bookings data that the tests can use
    name = "A.Playera/B.Playerb";
    court = 5;
    slot = 3;
    booking = new Booking(court, slot, name);
    bookings = new ArrayList<>();
    bookings.add(booking);
    redirectUrl = "redirectUrl.html";

    // Exception message thrown to apigateway invocations has a redirecturl
    // appended
    genericExceptionMessage = "Apologies - something has gone wrong. Please try again." + redirectUrl;
}

From source file:br.com.ifpb.bdnc.projeto.geo.servlets.CadastraImagem.java

private Image mountImage(HttpServletRequest request) {
    Image image = new Image();
    image.setCoord(new Coordenate());
    boolean isMultipart = ServletFileUpload.isMultipartContent(request);
    if (isMultipart) {
        ServletFileUpload upload = new ServletFileUpload();
        try {/*from   ww w.  jav a 2s  .  c  o m*/
            FileItemIterator itr = upload.getItemIterator(request);
            while (itr.hasNext()) {
                FileItemStream item = itr.next();
                if (item.isFormField()) {
                    InputStream in = item.openStream();
                    byte[] b = new byte[in.available()];
                    in.read(b);
                    if (item.getFieldName().equals("description")) {
                        image.setDescription(new String(b));
                    } else if (item.getFieldName().equals("authors")) {
                        image.setAuthors(new String(b));
                    } else if (item.getFieldName().equals("end")) {
                        image.setDate(
                                LocalDate.parse(new String(b), DateTimeFormatter.ofPattern("yyyy-MM-dd")));
                    } else if (item.getFieldName().equals("latitude")) {
                        image.getCoord().setLat(new String(b));
                    } else if (item.getFieldName().equals("longitude")) {
                        image.getCoord().setLng(new String(b));
                    } else if (item.getFieldName().equals("heading")) {
                        image.getCoord().setHeading(new String(b));
                    } else if (item.getFieldName().equals("pitch")) {
                        image.getCoord().setPitch(new String(b));
                    } else if (item.getFieldName().equals("zoom")) {
                        image.getCoord().setZoom(new String(b));
                    }
                } else {
                    if (!item.getName().equals("")) {
                        MultipartData md = new MultipartData();
                        String folder = "historicImages";
                        md.setFolder(folder);
                        String path = request.getServletContext().getRealPath("/");
                        System.out.println(path);
                        String nameToSave = "pubImage" + Calendar.getInstance().getTimeInMillis()
                                + item.getName();
                        image.setImagePath(folder + "/" + nameToSave);
                        md.saveImage(path, item, nameToSave);
                        String imageMinPath = folder + "/" + "min" + nameToSave;
                        RedimencionadorImagem.resize(path, folder + "/" + nameToSave,
                                path + "/" + imageMinPath.toString(), IMAGE_MIN_WIDTH, IMAGE_MIM_HEIGHT);
                        image.setMinImagePath(imageMinPath);
                    }
                }
            }
        } catch (FileUploadException | IOException ex) {
            System.out.println("Erro ao manipular dados");
        }
    }
    return image;
}