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:org.primeframework.mvc.parameter.convert.converters.LocalDateConverter.java

protected String objectToString(Object value, Type convertFrom, Map<String, String> attributes,
        String expression) throws ConversionException, ConverterStateException {
    String format = attributes.get("dateTimeFormat");
    if (format == null) {
        throw new ConverterStateException("You must provide the dateTimeFormat dynamic attribute for "
                + "the form fields [" + expression + "] that maps to LocalDate properties in the action. "
                + "If you are using a text field it will look like this: [@jc.text _dateTimeFormat=\"MM/dd/yyyy\"]");
    }/*from   w w w. j  av a 2s. c o m*/

    return ((LocalDate) value).format(DateTimeFormatter.ofPattern(format));
}

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

private static void log(String msg, Object... args) {
    DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy.MM.dd-HH:mm:ss");
    String date = LocalDateTime.now().format(formatter);
    System.out.printf("\n[%s] %s", date, String.format(msg, args));
}

From source file:org.ojbc.adapters.analyticaldatastore.personid.IndexedPersonIdentifierStrategyTest.java

private Object makeDate(int year, int monthOfYear, int dayOfMonth) {
    LocalDate today = LocalDate.of(year, monthOfYear, dayOfMonth);
    DateTimeFormatter dtf = DateTimeFormatter.ofPattern("uuuu-MM-dd");
    String dateTimeStamp = today.format(dtf);

    return dateTimeStamp;
}

From source file:com.oembedler.moon.graphql.engine.type.GraphQLLocalDateTimeType.java

public GraphQLLocalDateTimeType(String name, String description, String dateFormat) {
    super(name, description, new Coercing() {
        private final TimeZone timeZone = TimeZone.getTimeZone("UTC");

        @Override//w  ww. j  a  va2  s  .  com
        public Object serialize(Object input) {
            if (input instanceof String) {
                return parse((String) input);
            } else if (input instanceof LocalDateTime) {
                return format((LocalDateTime) input);
            } else if (input instanceof Long) {
                return LocalDateTime.ofEpochSecond((Long) input, 0, ZoneOffset.UTC);
            } else if (input instanceof Integer) {
                return LocalDateTime.ofEpochSecond((((Integer) input).longValue()), 0, ZoneOffset.UTC);
            } else {
                throw new GraphQLException("Wrong timestamp value");
            }
        }

        @Override
        public Object parseValue(Object input) {
            return serialize(input);
        }

        @Override
        public Object parseLiteral(Object input) {
            if (!(input instanceof StringValue))
                return null;
            return parse(((StringValue) input).getValue());
        }

        private String format(LocalDateTime input) {
            return getDateTimeFormatter().format(input);
        }

        private LocalDateTime parse(String input) {
            LocalDateTime date = null;
            try {
                date = LocalDateTime.parse(input, getDateTimeFormatter());
            } catch (Exception e) {
                throw new GraphQLException("Can not parse input date", e);
            }
            return date;
        }

        private DateTimeFormatter getDateTimeFormatter() {
            DateTimeFormatter formatter = DateTimeFormatter.ofPattern(dateFormat);
            return formatter;
        }
    });
    Assert.notNull(dateFormat, "Date format must not be null");
}

From source file:org.primeframework.mvc.parameter.convert.converters.LocalDateConverter.java

private LocalDate toLocalDate(String value, String format) {
    try {//from  w  w  w.j  av a 2s .  c o  m
        return LocalDate.parse(value, DateTimeFormatter.ofPattern(format));
    } catch (DateTimeParseException e) {
        throw new ConversionException("Invalid date [" + value + "] for format [" + format + "]", e);
    }
}

From source file:org.edgexfoundry.scheduling.ScheduleContext.java

public void reset(Schedule schedule) {
    if ((this.schedule != null) && (this.schedule.getName() != schedule.getName())) {
        scheduleEvents.clear();//from w ww  . ja  va 2s  .co m
    }
    this.schedule = schedule;
    // update this if/when iterations are added to the schedule
    this.maxIterations = (schedule.getRunOnce()) ? 1 : 0;
    this.iterations = 0;

    String start = schedule.getStart();
    String end = schedule.getEnd();
    // if start is empty, then use now (need to think about ever-spawning tasks)
    if (start == null || start.isEmpty()) {
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern(Schedule.DATETIME_FORMATS[0])
                .withZone(ZoneId.systemDefault());
        start = formatter.format(Instant.now());
    }
    this.startTime = parseTime(start);

    // if end is empty, then use max
    if (end == null || end.isEmpty()) {
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern(Schedule.DATETIME_FORMATS[0])
                .withZone(ZoneId.systemDefault());
        end = formatter.format(ZonedDateTime.of(LocalDateTime.MAX, ZoneId.systemDefault()));
    }
    this.endTime = parseTime(end);

    // get the period and duration from the frequency string
    parsePeriodAndDuration(schedule.getFrequency());

    // setup the next time the schedule will run
    this.nextTime = initNextTime(startTime, ZonedDateTime.now(), period, duration);

    // clear any schedule events as required

    logger.debug("reset() " + this.toString());
}

From source file:org.cloud.mblog.utils.FileUtil.java

/**
 * @param date localtime/*from   w w  w.  j  a  v a  2s . c  om*/
 * @return
 */
private static String getThumbRelativePathByDate(LocalDateTime date) {
    // ????
    DateTimeFormatter formatter = DateTimeFormatter.ofPattern(FILE_DATE_DIR_FMT);
    String datePath = THUMBNAIL + date.format(formatter);
    return getImageRelativePath(datePath);
}

From source file:org.wallride.service.BlogService.java

@CacheEvict(value = WallRideCacheConfiguration.BLOG_CACHE, allEntries = true)
public GoogleAnalytics updateGoogleAnalytics(GoogleAnalyticsUpdateRequest request) {
    byte[] p12;//w  ww .  j  ava2 s  .c  o  m
    try {
        p12 = request.getServiceAccountP12File().getBytes();
    } catch (IOException e) {
        throw new ServiceException(e);
    }

    try {
        PrivateKey privateKey = SecurityUtils.loadPrivateKeyFromKeyStore(SecurityUtils.getPkcs12KeyStore(),
                new ByteArrayInputStream(p12), "notasecret", "privatekey", "notasecret");

        HttpTransport httpTransport = GoogleNetHttpTransport.newTrustedTransport();
        JsonFactory jsonFactory = JacksonFactory.getDefaultInstance();

        // Build service account credential.
        Set<String> scopes = new HashSet<>();
        scopes.add(AnalyticsScopes.ANALYTICS_READONLY);

        GoogleCredential credential = new GoogleCredential.Builder().setTransport(httpTransport)
                .setJsonFactory(jsonFactory).setServiceAccountId(request.getServiceAccountId())
                .setServiceAccountScopes(scopes).setServiceAccountPrivateKey(privateKey).build();

        Analytics analytics = new Analytics.Builder(httpTransport, jsonFactory, credential)
                .setApplicationName("WallRide").build();

        GaData gaData = analytics.data().ga()
                .get(request.getProfileId(), "2005-01-01",
                        LocalDate.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd")), "ga:pageviews")
                .setDimensions(String.format("ga:dimension%d", request.getCustomDimensionIndex()))
                .setMaxResults(1).execute();
        logger.debug("GaData: {}", gaData);
    } catch (GeneralSecurityException e) {
        throw new GoogleAnalyticsException(e);
    } catch (IOException e) {
        throw new GoogleAnalyticsException(e);
    }

    GoogleAnalytics googleAnalytics = new GoogleAnalytics();
    googleAnalytics.setTrackingId(request.getTrackingId());
    googleAnalytics.setProfileId(request.getProfileId());
    googleAnalytics.setCustomDimensionIndex(request.getCustomDimensionIndex());
    googleAnalytics.setServiceAccountId(request.getServiceAccountId());
    googleAnalytics.setServiceAccountP12FileName(request.getServiceAccountP12File().getOriginalFilename());
    googleAnalytics.setServiceAccountP12FileContent(p12);

    Blog blog = blogRepository.findOneForUpdateById(request.getBlogId());
    blog.setGoogleAnalytics(googleAnalytics);

    blog = blogRepository.saveAndFlush(blog);
    return blog.getGoogleAnalytics();
}

From source file:svc.managers.SMSManagerTest.java

@Test
public void licenseReadMessageGetsGenerated() throws TwiMLException, ParseException {
    setStageInSession(session, SMS_STAGE.READ_LICENSE);
    session.setAttribute("dob", "06/01/1963");
    Citation citation = new Citation();
    DateTimeFormatter formatter = DateTimeFormatter.ofPattern("MM/dd/yyyy");
    citation.citation_date = LocalDate.parse("02/03/1990", formatter);
    List<Citation> citations = new ArrayList<Citation>();
    citations.add(citation);/*from  www  .  j  a  v  a2 s .  c  o  m*/

    when(citationManagerMock.findCitations((CitationSearchCriteria) notNull())).thenReturn(citations);

    TwimlMessageRequest twimlMessageRequest = new TwimlMessageRequest();
    twimlMessageRequest.setBody("F917801962");
    String message = "1 ticket was found\n1) ticket from: 02/03/1990\nReply with the ticket number you want to view.";
    MessagingResponse twimlResponse = manager.getTwimlResponse(twimlMessageRequest, requestMock, session);
    assertEquals(createTwimlResponse(message).toXml(), twimlResponse.toXml());
}

From source file:OandaProviderDriver.java

public ArrayList<SM230Candle> getRecentCandles(String instrument, String granularity, int count)
        throws ClientProtocolException, IOException {
    String normalized_instrument = instrument;

    // e.g., EUR/USD (ISO format) => EUR_USD (endpoint format)
    if (instrument.contains("/")) {
        normalized_instrument = instrument.replace("/", "_");
    }/*from  w  ww  .j av  a  2s. c  o m*/

    HttpClient client = HttpClientBuilder.create().build();
    HttpGet request = new HttpGet("https://api-fxtrade.oanda.com/v3/instruments/" + normalized_instrument
            + "/candles?count=" + String.valueOf(count) + "&price=M&granularity=" + granularity);

    System.out.println("Api KEY: " + apiKey);

    request.addHeader("Content-Type", "application/json");
    request.addHeader("Authorization", "Bearer " + apiKey);
    HttpResponse response = client.execute(request);
    BufferedReader rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
    String line = "", l = "";

    while ((l = rd.readLine()) != null) {
        line += l;
    }

    System.out.println("Line: " + line);

    JSONObject root = new JSONObject(line);
    JSONArray candles_json = root.getJSONArray("candles");
    JSONObject candle_json, mid;

    ArrayList<SM230Candle> candles = new ArrayList<>();

    for (int i = 0; i < candles_json.length(); i++) {
        candle_json = candles_json.getJSONObject(i);
        mid = candle_json.getJSONObject("mid");

        SM230Candle candle = new SM230Candle(instrument,
                LocalDateTime.parse(candle_json.get("time").toString(),
                        DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSSSSSSSSz")),
                granularity, Double.valueOf(mid.get("o").toString()), Double.valueOf(mid.get("h").toString()),
                Double.valueOf(mid.get("l").toString()), Double.valueOf(mid.get("c").toString()));

        candles.add(candle);
    }

    return candles;
}