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:Graphite.java

private String getDateAsString(long start) {
    DateTimeFormatter formatter = DateTimeFormatter.ofPattern("HH:mm_yyyyMMdd").withZone(zoneId);
    return formatter.format(Instant.ofEpochMilli(start));
}

From source file:fr.lepellerin.ecole.web.controller.cantine.DetaillerReservationRepasController.java

/**
 * init le model de la page details des reservations.
 *
 * @param model/* ww  w .  ja  v a2 s .c o m*/
 *          : model spring
 * @return le nom de la vue
 * @throws TechnicalException 
 */
@RequestMapping("/init")
public String init(final Model model, @ModelAttribute("command") DetaillerReservationRepasForm form)
        throws TechnicalException {
    final CurrentUser user = (CurrentUser) SecurityContextHolder.getContext().getAuthentication()
            .getPrincipal();

    final YearMonth moisActuel = YearMonth.parse(form.getAnneeMois().toString(),
            DateTimeFormatter.ofPattern(GeDateUtils.DATE_FORMAT_YYYYMM));

    final PlanningDto planning = this.cantineService.getDateOuvert(moisActuel, user.getUser().getFamille());

    model.addAttribute("planning", planning);

    return VUE;
}

From source file:eg.agrimarket.controller.EditProfileController.java

@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    try {/*from www .  ja v  a  2 s.c om*/

        DiskFileItemFactory factory = new DiskFileItemFactory();
        ServletFileUpload upload = new ServletFileUpload(factory);
        List<FileItem> items = upload.parseRequest(request);
        Iterator<FileItem> it = items.iterator();

        HttpSession session = request.getSession(false);
        User user = (User) session.getAttribute("user");
        if (user == null) {
            user = new User();
        }
        ArrayList<Interest> newInterests = new ArrayList<>();
        while (it.hasNext()) {
            FileItem item = it.next();
            if (!item.isFormField()) {
                byte[] image = item.get();
                if (image != null && image.length != 0) {
                    user.setImage(image);
                }
                //                    System.out.println(user.getImage());
            } else {
                switch (item.getFieldName()) {
                case "name":
                    user.setUserName(item.getString());
                    break;
                case "mail":
                    user.setEmail(item.getString());
                    break;
                case "password":
                    user.setPassword(item.getString());
                    break;
                case "job":
                    user.setJob(item.getString());
                    break;
                case "date":
                    DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
                    LocalDate date = LocalDate.parse(item.getString(), formatter);
                    user.setDOB(date);
                    break;
                case "address":
                    user.setAddress(item.getString());
                    break;
                case "credit":
                    user.setCreditNumber(item.getString());
                    break;
                default:

                    eg.agrimarket.model.dto.Interest interest = new eg.agrimarket.model.dto.Interest();
                    interest.setId(Integer.parseInt(item.getString()));
                    interest.setName(item.getFieldName());
                    newInterests.add(interest);
                    System.out.println(item.getFieldName() + " : " + item.getString());
                }
            }
        }
        user.setInterests(newInterests);
        UserDaoImpl userDao = new UserDaoImpl();
        userDao.updateUser(user);

        session.setAttribute("user", user);
    } catch (FileUploadException ex) {
        Logger.getLogger(EditProfileController.class.getName()).log(Level.SEVERE, null, ex);
    } catch (Exception ex) {
        Logger.getLogger(EditProfileController.class.getName()).log(Level.SEVERE, null, ex);
    }
    response.sendRedirect("profile.jsp");
}

From source file:svc.data.citations.datasources.mock.MockCitationDataSourceIntegrationTest.java

@Test
public void CitationWithNullDateValuesIsCorrectlyHandled() throws ParseException {
    String dateString = "02/24/1987";
    DateTimeFormatter formatter = DateTimeFormatter.ofPattern("MM/dd/yyyy");
    LocalDate date = LocalDate.parse(dateString, formatter);

    List<Citation> citations = mockCitationDataSource.getByLicenseAndDOB("N806453191", "MO", date);
    assertThat(citations.get(0).citation_date, is(nullValue()));

    dateString = "11/21/1994";
    date = LocalDate.parse(dateString, formatter);
    citations = mockCitationDataSource.getByLicenseAndDOB("E501444452", "MO", date);
    assertThat(citations.get(0).court_dateTime, is(nullValue()));
}

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

public ComparativeTimeQualifiedPointAccessibility(final PathScoreCard scoreCard,
        final PathScoreCard trialScoreCard, final Grid grid, final Center centerPoint, final LocalDateTime time,
        LocalDateTime trialTime, final Duration tripDuration, final boolean backward, final String name,
        final String trialName, final Duration inServiceTime, final Duration trialInServiceTime)
        throws InterruptedException {

    type = AccessibilityType.COMPARATIVE_TIME_QUALIFIED_POINT_ACCESSIBILITY;
    direction = backward ? Direction.INBOUND : Direction.OUTBOUND;
    mapBounds = new Bounds(grid.getBounds());
    center = new Point(centerPoint.getLogicalCenter().getPointRepresentation());
    this.time = time.format(DateTimeFormatter.ofPattern("YYYY-MM-dd HH:mm:ss"));
    this.trialTime = trialTime.format(DateTimeFormatter.ofPattern("YYYY-MM-dd HH:mm:ss"));

    this.tripDuration = DurationFormatUtils.formatDurationWords(tripDuration.toMillis(), true, true);
    final ImmutableMap.Builder<Bounds, ComparativeFullSectorReachInformation> builder = ImmutableMap.builder();

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

    final TaskIdentifier task = new TaskIdentifier(time, centerPoint);
    for (final Sector sector : sectors) {
        final MovementPath sectorPath = scoreCard.getBestPath(sector, task);
        final MovementPath trialSectorPath = trialScoreCard.getBestPath(sector, task);
        if (sectorPath != null || trialSectorPath != null) {
            final Bounds sectorBounds = new Bounds(sector);

            builder.put(sectorBounds, new ComparativeFullSectorReachInformation(sectorPath, trialSectorPath));
        }/*from  ww  w .ja v  a  2  s.  c om*/
    }
    sectorPaths = builder.build();
    totalSectors = grid.getReachableSectors().size();
    this.name = name;
    this.trialName = trialName;
    inServiceSeconds = inServiceTime.getSeconds();
    trialInServiceSeconds = trialInServiceTime.getSeconds();
}

From source file:controller.EditProfileController.java

@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    try {/*from ww w. j a  v a2  s.  com*/

        DiskFileItemFactory factory = new DiskFileItemFactory();
        ServletFileUpload upload = new ServletFileUpload(factory);
        List<FileItem> items = upload.parseRequest(request);
        Iterator<FileItem> it = items.iterator();

        HttpSession session = request.getSession(false);
        User user = (User) session.getAttribute("user");
        if (user == null) {
            user = new User();
        }
        ArrayList<String> newInterests = new ArrayList<>();
        while (it.hasNext()) {
            FileItem item = it.next();
            if (!item.isFormField()) {
                byte[] image = item.get();
                if (image != null && image.length != 0) {
                    user.setImage(image);
                }
                //                    System.out.println(user.getImage());
            } else {
                switch (item.getFieldName()) {
                case "name":
                    user.setUserName(item.getString());
                    break;
                case "mail":
                    user.setEmail(item.getString());
                    break;
                case "password":
                    user.setPassword(item.getString());
                    break;
                case "job":
                    user.setJob(item.getString());
                    break;
                case "date":
                    DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
                    LocalDate date = LocalDate.parse(item.getString(), formatter);
                    user.setDOB(date);
                    break;
                case "address":
                    user.setAddress(item.getString());
                    break;
                case "credit":
                    user.setCreditNumber(item.getString());
                    break;
                default:
                    newInterests.add(item.getString());
                    //                            System.out.println(item.getFieldName() + " : " + item.getString());
                }
            }
        }
        user.setInterests(newInterests);
        UserDaoImpl userDao = new UserDaoImpl();
        userDao.updateUser(user);

        session.setAttribute("user", user);
        //            System.out.println(user.getInterests());
        //            System.out.println(user.getImage());
    } catch (FileUploadException ex) {
        Logger.getLogger(EditProfileController.class.getName()).log(Level.SEVERE, null, ex);
    } catch (Exception ex) {
        Logger.getLogger(EditProfileController.class.getName()).log(Level.SEVERE, null, ex);
    }
    response.sendRedirect("profile.jsp");
}

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

public ComparativeNetworkAccessibility(final int taskCount, final int trialTaskCount, final ScoreCard scoreCard,
        final ScoreCard trialScoreCard, final Grid grid, final Set<Sector> centerSectors,
        final LocalDateTime startTime, final LocalDateTime endTime, final LocalDateTime trialStartTime,
        final LocalDateTime trialEndTime, final Duration tripDuration, final Duration samplingInterval,
        final boolean backward, final String trialName, final Duration inServiceTime,
        final Duration trialInServiceTime) throws InterruptedException {
    type = AccessibilityType.COMPARATIVE_NETWORK_ACCESSIBILITY;

    direction = backward ? Direction.INBOUND : Direction.OUTBOUND;
    mapBounds = new Bounds(grid.getBounds());
    boundsCenter = new Point(grid.getBounds().getCenter());
    this.startTime = startTime.format(DateTimeFormatter.ofPattern("YYYY-MM-dd HH:mm:ss"));
    this.endTime = endTime.format(DateTimeFormatter.ofPattern("YYYY-MM-dd HH:mm:ss"));
    this.trialStartTime = trialStartTime.format(DateTimeFormatter.ofPattern("YYYY-MM-dd HH:mm:ss"));
    this.trialEndTime = trialEndTime.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;
    this.trialTaskCount = trialTaskCount;

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

    final ImmutableMap.Builder<Bounds, CountComparison> countBuilder = ImmutableMap.builder();
    for (final Sector sector : sectors) {
        final int count = scoreCard.hasPath(sector) ? scoreCard.getReachedCount(sector) : 0;
        final int trialCount = trialScoreCard.hasPath(sector) ? trialScoreCard.getReachedCount(sector) : 0;

        if (count != 0 && trialCount != 0) {
            final Bounds bounds = new Bounds(sector);
            final CountComparison comparison = new CountComparison(count, trialCount);
            countBuilder.put(bounds, comparison);
        }/*from  w w  w  .  j a  v a 2s.  c om*/
    }

    sectorCounts = countBuilder.build();

    this.centerPoints = centerSectors.stream().map(sector -> new Point(sector.getBounds().getCenter()))
            .collect(Collectors.toSet());
    sampleCount = centerPoints.size();

    this.trialName = trialName;

    inServiceSeconds = inServiceTime.getSeconds();
    trialInServiceSeconds = trialInServiceTime.getSeconds();
}

From source file:cc.kave.commons.utils.exec.CompletionEventProcessor.java

private static void log(String msg, Object... args) {
    DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyMMddHHmmss");
    String date = LocalDateTime.now().format(formatter);
    System.out.printf("\n%s %s", date, String.format(msg, args));
}

From source file:com.intuit.wasabi.api.pagination.filters.FilterUtil.java

/**
 * Formats a date as it is shown in the UI to allow for matching searches on date fields.
 * Needs the requesting user's timezone offset to UTC for correct matches.
 *
 * @param date           the date/*from ww  w .jav a2  s . c  o  m*/
 * @param timeZoneOffset the timezone offset to UTC
 * @return a timezone offset adjusted string of the UI pattern {@code MMM d, YYYY HH:mm:ss a}.
 */
/*test*/
static String formatDateTimeAsUI(OffsetDateTime date, String timeZoneOffset) {
    try {
        return date.format(DateTimeFormatter.ofPattern("MMM d, YYYY HH:mm:ss a")
                .withZone(ZoneId.ofOffset("UTC", ZoneOffset.of(timeZoneOffset))));
    } catch (DateTimeException dateTimeException) {
        throw new PaginationException(ErrorCode.FILTER_KEY_UNPROCESSABLE,
                "Wrong format: Can not parse timezone '" + timeZoneOffset + "' or date " + date.toString()
                        + " properly.",
                dateTimeException);
    }
}

From source file:org.apache.metron.parsers.snort.BasicSnortParser.java

private DateTimeFormatter getDateFormatter(Map<String, Object> parserConfig) {
    String format = (String) parserConfig.get("dateFormat");
    if (StringUtils.isNotEmpty(format)) {
        _LOG.info("Using date format '{}'", format);
        return DateTimeFormatter.ofPattern(format);
    } else {/* ww w .j  av a  2 s  .c  om*/
        _LOG.info("Using default date format '{}'", defaultDateFormat);
        return DateTimeFormatter.ofPattern(defaultDateFormat);
    }
}