List of usage examples for java.time.format DateTimeFormatter ofPattern
public static DateTimeFormatter ofPattern(String pattern, Locale locale)
From source file:sh.scrap.scrapper.functions.DateFunctionFactory.java
private ZonedDateTime parse(String data, String pattern, Locale locale, ZoneId zoneId) { DateTimeFormatter format = DateTimeFormatter.ofPattern(pattern, locale).withZone(zoneId); return ZonedDateTime.parse(data, format); }
From source file:sh.scrap.scrapper.functions.DateFunctionFactory.java
private String format(ZonedDateTime data, String pattern, Locale locale, ZoneId zoneId) { DateTimeFormatter format = DateTimeFormatter.ofPattern(pattern, locale).withZone(zoneId); return data.format(format); }
From source file:org.codelibs.fess.taglib.FessFunctions.java
public static String formatDate(final LocalDateTime date) { if (date == null) { return StringUtil.EMPTY; }//from w ww . j a v a 2 s . c om return date.format(DateTimeFormatter.ofPattern(Constants.ISO_DATETIME_FORMAT, Locale.ROOT)); }
From source file:rapture.dp.invocable.calendar.steps.CalendarLookupStep.java
@Override public String invoke(CallingContext ctx) { DecisionApi decision = Kernel.getDecision(); try {/*ww w .jav a 2s . c o m*/ decision.setContextLiteral(ctx, getWorkerURI(), "STEPNAME", getStepName()); String dateStr = StringUtils.stripToNull(decision.getContextValue(ctx, getWorkerURI(), "DATE")); String calendar = StringUtils.stripToNull(decision.getContextValue(ctx, getWorkerURI(), "CALENDAR")); String translator = StringUtils .stripToNull(decision.getContextValue(ctx, getWorkerURI(), "TRANSLATOR")); if (translator == null) translator = StringUtils .stripToNull(decision.getContextValue(ctx, getWorkerURI(), "DEFAULT_TRANSLATOR")); LocalDate date = (dateStr == null) ? LocalDate.now() : LocalDate.parse(dateStr); // Translate the date to a name - eg Good Friday, Yom Kippur, Thanksgiving // Expected format is a map of dates (with or without years) to names or lists of names // Example: // { // "31Dec" : ["New Tear's Eve", "Hogmanay"] , // "05Sep2016" : "Labor Day", // "04Sep2017" : "Labor Day" // "2015-01-01" : "New Year's Day" // } Map<String, Object> calendarTable = new HashMap<>(); if (calendar != null) { String calendarJson = StringUtils.stripToNull(Kernel.getDoc().getDoc(ctx, calendar)); if (calendarJson != null) { calendarTable = JacksonUtil.getMapFromJson(calendarJson); } } // Translate the date to a name - eg Good Friday, Yom Kippur, Thanksgiving Map<String, Object> translationTable = new HashMap<>(); if (translator != null) { String translationJson = StringUtils.stripToNull(Kernel.getDoc().getDoc(ctx, translator)); if (translationJson != null) { translationTable = JacksonUtil.getMapFromJson(translationJson); } } List<String> lookup = new ArrayList<>(); String languageTag = StringUtils.stripToNull(decision.getContextValue(ctx, getWorkerURI(), "LOCALE")); Locale locale = (languageTag == null) ? Locale.getDefault() : Locale.forLanguageTag(languageTag); for (DateTimeFormatter formatter : ImmutableList.of(DateTimeFormatter.ISO_LOCAL_DATE, DateTimeFormatter.ofPattern("ddMMMuuuu", locale), DateTimeFormatter.ofPattern("ddMMM", locale), DateTimeFormatter.ofPattern("MMMdduuuu", locale), DateTimeFormatter.ofPattern("MMMdd", locale), DateTimeFormatter.ofPattern("uuuuMMMdd", locale))) { String formattedDate = date.format(formatter); Object transList = translationTable.get(formattedDate); if (transList != null) { if (transList instanceof Iterable) { for (Object o : (Iterable) transList) { lookup.add(o.toString()); } } else lookup.add(transList.toString()); } lookup.add(formattedDate); } lookup.add(DayOfWeek.from(date).getDisplayName(TextStyle.FULL, locale)); decision.setContextLiteral(ctx, getWorkerURI(), "DATE_TRANSLATIONS", JacksonUtil.jsonFromObject(lookup)); // Calendar table defines the priority. getMapFromJson returns a LinkedHashMap so order is preserved. for (Entry<String, Object> calEntry : calendarTable.entrySet()) { if (lookup.contains(calEntry.getKey())) { decision.setContextLiteral(ctx, getWorkerURI(), "CALENDAR_LOOKUP_ENTRY", JacksonUtil.jsonFromObject(calEntry)); decision.writeWorkflowAuditEntry(ctx, getWorkerURI(), calEntry.getKey() + " matched as " + calEntry.getValue().toString(), false); return calEntry.getValue().toString(); } } decision.writeWorkflowAuditEntry(ctx, getWorkerURI(), getStepName() + ": No matches for " + DateTimeFormatter.ISO_LOCAL_DATE.format(date) + " found in calendar", false); return getNextTransition(); } catch (Exception e) { decision.setContextLiteral(ctx, getWorkerURI(), getStepName(), "Unable to access the calendar : " + e.getLocalizedMessage()); decision.setContextLiteral(ctx, getWorkerURI(), getStepName() + "Error", ExceptionToString.summary(e)); decision.writeWorkflowAuditEntry(ctx, getWorkerURI(), "Problem in " + getStepName() + ": " + ExceptionToString.getRootCause(e).getLocalizedMessage(), true); return getErrorTransition(); } }
From source file:org.talend.dataquality.statistics.datetime.DateTimePatternManager.java
private static boolean isMatchCustomPattern(String value, String customPattern, Locale locale) { if (customPattern == null) { return false; }/* w w w. j ava 2s . c om*/ try {// firstly, try with user-defined locale DateTimeFormatter.ofPattern(customPattern, locale).parse(value); return true; } catch (DateTimeParseException | IllegalArgumentException e) { if (!DEFAULT_LOCALE.equals(locale)) { try {// try with LOCALE_US if user defined locale is not US DateTimeFormatter.ofPattern(customPattern, DEFAULT_LOCALE).parse(value); return true; } catch (DateTimeParseException | IllegalArgumentException e1) { // return false } } } return false; }
From source file:org.flockdata.transform.ExpressionHelper.java
public static Long parseDate(ColumnDefinition colDef, String value) { if (value == null || value.equals("")) return null; if (colDef.isDateEpoc()) { return Long.parseLong(value) * 1000; }// ww w.j a va 2s .com if (colDef.getDateFormat() == null || colDef.getDateFormat().equalsIgnoreCase("automatic")) { try { return Date.parse(value); } catch (IllegalArgumentException e) { // Try other formats } } if (colDef.getDateFormat() != null && colDef.getDateFormat().equalsIgnoreCase("timestamp")) { try { return Timestamp.valueOf(value).getTime(); } catch (IllegalArgumentException e) { // attempt other conversions } } if (NumberUtils.isDigits(value)) // plain old java millis return Long.parseLong(value); // Custom Date formats String tz = colDef.getTimeZone(); if (tz == null) tz = TimeZone.getDefault().getID(); try { // Try first as DateTime return new SimpleDateFormat(colDef.getDateFormat()).parse(value).getTime(); } catch (DateTimeParseException | IllegalArgumentException | ParseException e) { // Just a plain date DateTimeFormatter pattern = DateTimeFormatter.ofPattern(colDef.getDateFormat(), Locale.ENGLISH); LocalDate date = LocalDate.parse(value, pattern); return new DateTime(date.toString(), DateTimeZone.forID(tz)).getMillis(); } }
From source file:de.jfachwert.rechnung.Rechnungsmonat.java
private static LocalDate guessLocalDate(String monat, DateTimeParseException ex) { String[] datePatterns = { "d-MMM-yyyy", "d-MM-yyyy", "yyyy-MMM-d", "yyyy-MM-d", "MMM-d-yyyy" }; for (String pattern : datePatterns) { for (Locale locale : Locale.getAvailableLocales()) { try { return LocalDate.parse(monat, DateTimeFormatter.ofPattern(pattern, locale)); } catch (DateTimeParseException ignored) { ex.addSuppressed(new IllegalArgumentException( ignored.getMessage() + " / '" + monat + "' does not match '" + pattern + "'")); }//from www . j av a2 s. c om } } throw new InvalidValueException(monat, MONTH, ex); }
From source file:org.millr.slick.servlets.item.EditItemServlet.java
private Date convertDate(String publishString) { DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm", Locale.ENGLISH); LocalDateTime dateTime = LocalDateTime.parse(publishString, formatter); Date publishDate = Date.from(dateTime.atZone(ZoneId.systemDefault()).toInstant()); return publishDate; }
From source file:org.jboss.as.test.integration.logging.formatters.JsonFormatterTestCase.java
@Test public void testDateFormat() throws Exception { configure(Collections.emptyMap(), Collections.emptyMap(), false); final String dateFormat = "yyyy-MM-dd'T'HH:mm:ssSSSZ"; final String timezone = "GMT"; // Change the date format and time zone final CompositeOperationBuilder builder = CompositeOperationBuilder.create(); builder.addStep(Operations.createWriteAttributeOperation(FORMATTER_ADDRESS, "date-format", dateFormat)); builder.addStep(Operations.createWriteAttributeOperation(FORMATTER_ADDRESS, "zone-id", timezone)); executeOperation(builder.build());/*from ww w . ja va 2 s . c om*/ final String msg = "Logging test: JsonFormatterTestCase.testNoExceptions"; int statusCode = getResponse(msg, Collections.singletonMap(LoggingServiceActivator.LOG_EXCEPTION_KEY, "false")); Assert.assertTrue("Invalid response statusCode: " + statusCode, statusCode == HttpStatus.SC_OK); final List<String> expectedKeys = createDefaultKeys(); for (String s : Files.readAllLines(logFile, StandardCharsets.UTF_8)) { if (s.trim().isEmpty()) continue; try (JsonReader reader = Json.createReader(new StringReader(s))) { final JsonObject json = reader.readObject(); validateDefault(json, expectedKeys, msg); validateStackTrace(json, false, false); // Validate the date format is correct. We don't want to validate the specific date, only that it's // parsable. final String jsonDate = json.getString("timestamp"); // If the date is not parsable an exception should be thrown try { DateTimeFormatter.ofPattern(dateFormat, Locale.ROOT).withZone(ZoneId.of(timezone)) .parse(jsonDate); } catch (Exception e) { Assert.fail(String.format("Failed to parse %s with pattern %s and zone %s: %s", jsonDate, dateFormat, timezone, e.getMessage())); } } } }
From source file:org.jboss.as.test.integration.logging.formatters.XmlFormatterTestCase.java
@Test public void testDateFormat() throws Exception { configure(Collections.emptyMap(), Collections.emptyMap(), false); final String dateFormat = "yyyy-MM-dd'T'HH:mm:ssSSSZ"; final String timezone = "GMT"; // Change the date format and time zone final CompositeOperationBuilder builder = CompositeOperationBuilder.create(); builder.addStep(Operations.createWriteAttributeOperation(FORMATTER_ADDRESS, "date-format", dateFormat)); builder.addStep(Operations.createWriteAttributeOperation(FORMATTER_ADDRESS, "zone-id", timezone)); executeOperation(builder.build());// w w w. j av a 2 s .co m final String msg = "Logging test: XmlFormatterTestCase.testNoExceptions"; int statusCode = getResponse(msg, Collections.singletonMap(LoggingServiceActivator.LOG_EXCEPTION_KEY, "false")); Assert.assertEquals("Invalid response statusCode: " + statusCode, statusCode, HttpStatus.SC_OK); final List<String> expectedKeys = createDefaultKeys(); final DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); final DocumentBuilder documentBuilder = factory.newDocumentBuilder(); for (String s : Files.readAllLines(logFile, StandardCharsets.UTF_8)) { if (s.trim().isEmpty()) continue; final Document doc = documentBuilder.parse(new InputSource(new StringReader(s))); validateDefault(doc, expectedKeys, msg); validateStackTrace(doc, false, false); // Validate the date format is correct. We don't want to validate the specific date, only that it's // parsable. final NodeList timestampNode = doc.getElementsByTagName("timestamp"); Assert.assertEquals(1, timestampNode.getLength()); final String xmlDate = timestampNode.item(0).getTextContent(); // If the date is not parsable an exception should be thrown try { DateTimeFormatter.ofPattern(dateFormat, Locale.ROOT).withZone(ZoneId.of(timezone)).parse(xmlDate); } catch (Exception e) { Assert.fail(String.format("Failed to parse %s with pattern %s and zone %s: %s", xmlDate, dateFormat, timezone, e.getMessage())); } } }