List of usage examples for java.time.format DateTimeFormatter ofPattern
public static DateTimeFormatter ofPattern(String pattern, Locale locale)
From source file:org.talend.dataquality.statistics.datetime.utils.PatternListGenerator.java
private static String getFormattedDateTime(String pattern, Locale locale) { DateTimeFormatter formatter = DateTimeFormatter.ofPattern(pattern, locale); try {/*from ww w . j ava2 s . c o m*/ String formattedDateTime = ZONED_DATE_TIME.format(formatter); return formattedDateTime; } catch (Throwable t) { return t.getMessage(); } }
From source file:net.resheim.eclipse.timekeeper.ui.Activator.java
/** * Must be called by the UI-thread//from w w w . j a v a2 s . c o m * * @param idleTimeMillis */ private void handleReactivation(long idleTimeMillis) { // We want only one dialog open. if (dialogIsOpen) { return; } synchronized (this) { if (idleTimeMillis < lastIdleTime && lastIdleTime > IDLE_INTERVAL) { // If we have an active task ITask task = TasksUi.getTaskActivityManager().getActiveTask(); if (task != null && Activator.getValue(task, Activator.START) != null) { dialogIsOpen = true; String tickString = Activator.getValue(task, Activator.TICK); LocalDateTime started = getActiveSince(); LocalDateTime ticked = LocalDateTime.parse(tickString); LocalDateTime lastTick = ticked; // Subtract the IDLE_INTERVAL time the computer _was_ // idle while counting up to the threshold. During this // period fields were updated. Thus must be adjusted for. ticked = ticked.minusNanos(IDLE_INTERVAL); String time = DurationFormatUtils.formatDuration(lastIdleTime, "H:mm:ss", true); StringBuilder sb = new StringBuilder(); if (task.getTaskKey() != null) { sb.append(task.getTaskKey()); sb.append(": "); } sb.append(task.getSummary()); MessageDialog md = new MessageDialog(Display.getCurrent().getActiveShell(), "Disregard idle time?", null, MessageFormat.format( "The computer has been idle since {0}, more than {1}. The active task \"{2}\" was started on {3}. Deactivate the task and disregard the idle time?", ticked.format(DateTimeFormatter.ofPattern("EEE e, HH:mm:ss", Locale.US)), time, sb.toString(), started.format(DateTimeFormatter.ofPattern("EEE e, HH:mm:ss", Locale.US))), MessageDialog.QUESTION, new String[] { "No", "Yes" }, 1); int open = md.open(); dialogIsOpen = false; if (open == 1) { // Stop task, subtract initial idle time TasksUi.getTaskActivityManager().deactivateTask(task); reduceTime(task, ticked.toLocalDate().toString(), IDLE_INTERVAL / 1000); } else { // Continue task, add idle time LocalDateTime now = LocalDateTime.now(); long seconds = lastTick.until(now, ChronoUnit.MILLIS); accumulateTime(task, ticked.toLocalDate().toString(), seconds); Activator.setValue(task, Activator.TICK, now.toString()); } } } } }
From source file:de.jfachwert.rechnung.Rechnungsmonat.java
/** * Hiermit kann der Rechnungsmonats im gewuenschten Format ausgegeben * werden. Als Parameter sind die gleichen Patterns wie beim * {@link DateTimeFormatter#ofPattern(String, Locale)} bzw. * {@link java.text.SimpleDateFormat} moeglich. * * @param pattern z.B. "MM/yyyy"/*from w w w. ja v a 2s .c om*/ * @param locale gewuenschte Locale * @return z.B. "07/2017" */ public String format(String pattern, Locale locale) { DateTimeFormatter formatter = DateTimeFormatter.ofPattern(pattern, locale); return asLocalDate().format(formatter); }
From source file:org.talend.dataquality.statistics.datetime.utils.PatternListGenerator.java
private static void generateDateFormats() throws IOException { int currentLocaledPatternSize = 0; knownLocaledPatternList.clear();/* w w w . j ava 2s . c o m*/ knownPatternList.clear(); // 1. Base Localized DateTimePatterns (java8 DateTimeFormatterBuilder) processBaseDateTimePatternsByLocales(); int basePatternCount = knownLocaledPatternList.size() - currentLocaledPatternSize; if (PRINT_DETAILED_RESULTS) { System.out.println("#basePatterns = " + basePatternCount + "\n"); } currentLocaledPatternSize = knownLocaledPatternList.size(); // 2. Other common DateTime patterns for (LocaledPattern lp : OTHER_COMMON_PATTERNS_NEED_COMBINATION) { addLocaledPattern(lp); for (Locale locale : primaryLocaleArray) { String patternShort = DateTimeFormatterBuilder.getLocalizedDateTimePattern(// null, FormatStyle.SHORT, IsoChronology.INSTANCE, locale);// LocaledPattern combinedShortLP = new LocaledPattern(lp.pattern + " " + patternShort, locale, FormatStyle.SHORT.name(), true); addLocaledPattern(combinedShortLP); String patternMedium = DateTimeFormatterBuilder.getLocalizedDateTimePattern(// null, FormatStyle.MEDIUM, IsoChronology.INSTANCE, locale);// LocaledPattern combinedMediumLP = new LocaledPattern(lp.pattern + " " + patternMedium, locale, FormatStyle.MEDIUM.name(), true); addLocaledPattern(combinedMediumLP); } } for (LocaledPattern lp : OTHER_COMMON_PATTERNS) { addLocaledPattern(lp); } // 3. ISO and RFC DateTimePatterns processISOAndRFCDateTimePatternList(); // knownPatternList.addAll(isoPatternList); int isoPatternCount = knownLocaledPatternList.size() - currentLocaledPatternSize; if (PRINT_DETAILED_RESULTS) { System.out.println("#DateTimePattern(ISO&RFC) = " + isoPatternCount + "\n"); } currentLocaledPatternSize = knownLocaledPatternList.size(); // 4. Additional Localized DateTimePatterns (java8 DateTimeFormatterBuilder) processAdditionalDateTimePatternsByLocales(); // knownPatternList.addAll(additionalPatternList); int additionalPatternCount = knownLocaledPatternList.size() - currentLocaledPatternSize; if (PRINT_DETAILED_RESULTS) { System.out.println("#additionalPatternList = " + additionalPatternCount + "\n"); } currentLocaledPatternSize = knownLocaledPatternList.size(); if (PRINT_DETAILED_RESULTS) { System.out.println("#Total = " + knownLocaledPatternList.size() + // " (#baseDatePatterns = " + basePatternCount + // ", #isoPatterns = " + isoPatternCount + // ", #additionalPatterns = " + additionalPatternCount + ")\n");// } // table header dateSampleFileTextBuilder.append("Sample\tPattern\tLocale\tFormatStyle\tIsWithTime\n"); RegexGenerator regexGenerator = new RegexGenerator(); for (LocaledPattern lp : knownLocaledPatternList) { datePatternFileTextBuilder.append(lp).append("\n"); String regex = regexGenerator.convertPatternToRegex(lp.pattern); dateRegexFileTextBuilder.append(lp.getPattern()).append("\t^").append(regex).append("$\n"); dateSampleFileTextBuilder .append(ZONED_DATE_TIME.format(DateTimeFormatter.ofPattern(lp.getPattern(), lp.getLocale()))) .append("\t").append(lp.getPattern())// .append("\t").append(lp.getLocale())// .append("\t").append(lp.getFormatStyle())// .append("\t").append(lp.isWithTime()).append("\n"); } // Date Formats String path = SystemDateTimePatternManager.class.getResource("DateFormats.txt").getFile().replace( "target" + File.separator + "classes", "src" + File.separator + "main" + File.separator + "resources"); IOUtils.write(datePatternFileTextBuilder.toString(), new FileOutputStream(new File(path))); // Date Regexes path = SystemDateTimePatternManager.class.getResource("DateRegexes.txt").getFile().replace( "target" + File.separator + "classes", "src" + File.separator + "main" + File.separator + "resources"); IOUtils.write(dateRegexFileTextBuilder.toString(), new FileOutputStream(new File(path))); // Date Samples path = SystemDateTimePatternManager.class.getResource("DateSampleTable.txt").getFile().replace( "target" + File.separator + "classes", "src" + File.separator + "test" + File.separator + "resources"); IOUtils.write(dateSampleFileTextBuilder.toString(), new FileOutputStream(new File(path))); // generate grouped Date Regexes FormatGroupGenerator.generateDateRegexGroups(); }
From source file:investiagenofx2.view.InvestiaGenOFXController.java
private void getTransactionsFromWeb() { try {/*www . j a v a 2 s.c om*/ if (!htmlPage.getUrl().toString().contains("/TransactionReports/Select")) { if (InvestiaGenOFX.debug) { htmlPage = InvestiaGenOFX.getWebClient() .getPage(InvestiaGenOFX.debugFullPath + "-Transactions.htm"); } else { htmlPage = InvestiaGenOFX.getWebClient() .getPage(txt_investiaURL.getText() + "/TransactionReports/Select" + "?wcag=true"); waitForGeneratedTransactions(); } } @SuppressWarnings(("unchecked")) List<HtmlHeading4> h4from = (List<HtmlHeading4>) htmlPage .getByXPath("//h4[contains(text(),'Priode: de ')]"); String from = h4from.get(0).asText(); int index = from.indexOf("Priode: de "); LocalDate selFromDate = LocalDate.parse(from.substring(index + 12, index + 12 + 10)); if (dtp_lastDate.getValue().isBefore(selFromDate)) { @SuppressWarnings(("unchecked")) List<HtmlForm> forms = (List<HtmlForm>) htmlPage.getByXPath("//form"); HtmlForm form = forms.get(1); HtmlTextInput selPerFrom = form.getInputByName("selPerFrom"); selPerFrom.setValueAttribute(dtp_lastDate.getValue().toString()); HtmlAnchor generate = (HtmlAnchor) form.getByXPath("//a[contains(@class, 'btn-investia-blue')]") .get(0); if (InvestiaGenOFX.debug) { htmlPage = InvestiaGenOFX.getWebClient() .getPage(InvestiaGenOFX.debugFullPath + "-Transactions.htm"); } else { htmlPage = generate.click(); waitForGeneratedTransactions(); } } HtmlTable htmlTable = (HtmlTable) htmlPage.getElementById("tblTransactionReports"); if (htmlTable == null) { return; } for (int i = 0; i < htmlTable.getRowCount(); i++) { LocalDate transacDate = LocalDate.parse(htmlTable.getCellAt(i, 0).getTextContent(), DateTimeFormatter.ofPattern("dd MMM yyyy", Locale.CANADA_FRENCH)); if (transacDate.isBefore(dtp_lastDate.getValue())) { break; } String transacType = htmlTable.getCellAt(i, 2).getTextContent(); String[] token = transacType.split("[\\-/(]"); switch (token[0].replace(" ", "")) { case "Dividendes": transacType = "Distribution"; break; case "Achat": case "changeentrant": case "Prlvementautomatique": case "Transfertentrantdecourtier": case "Transfertexterneentrant": case "Transfertinterneentrant": transacType = "Purchase"; break; case "changesortant": case "Rachat": case "Transfertexternesortant": case "Transf.int.sort.": case "Transf.Int.sortant": case "Transfertinternesortant": transacType = "Switch Out"; break; case "Dpt": transacType = "Credit"; break; case "Retrait": case "Retenue": transacType = "Debit"; break; case "Crditenespces": case "Entred'espces": case "Fraisd'administration": case "Sortied'espces": case "Transfertd'espcesentrant": case "Transfertd'espcessortant": continue; default: try { throw new MyOwnException("Type de transaction non prise en charge: " + transacType.trim()); } catch (MyOwnException ex) { Logger.getLogger(OFXUtilites.class.getName()).log(Level.SEVERE, null, ex); continue; } } String transacAccount = accountOwnerName.split(" ")[0] + "\\" + htmlTable.getCellAt(i, 1).getTextContent(); String symbol = htmlTable.getCellAt(i, 3).getTextContent(); String unit = htmlTable.getCellAt(i, 5).getTextContent().replaceAll("[^0-9,]", "").replace(",", "."); String fitid = ""; String price = "0.00"; String amount; if ("Credit".equals(transacType) || "Debit".equals(transacType)) { amount = htmlTable.getCellAt(i, 9).getTextContent().replaceAll("[^0-9,]", "").replace(",", "."); fitid = StringUtils.stripAccents(htmlTable.getCellAt(i, 2).getTextContent()); } else { amount = htmlTable.getCellAt(i, 10).getTextContent().replaceAll("[^0-9,]", "").replace(",", "."); price = Float.toString(Float.parseFloat(amount) / Float.parseFloat(unit)); } if (PropertiesInit.getLinkAccountsTransac().indexOf(transacAccount) < 0) { linkAccountTransac(transacAccount); } int idxAccount = linkAccountToLocalAccountIndex[PropertiesInit.getLinkAccountsTransac() .indexOf(transacAccount)]; accounts.get(idxAccount) .add(new Transaction(transacDate, transacType, amount, fitid, symbol, unit, price, "")); } } catch (Exception ex) { Logger.getLogger(InvestiaGenOFXController.class.getName()).log(Level.SEVERE, null, ex); } }
From source file:org.talend.dataquality.statistics.datetime.utils.PatternListGenerator.java
private static void generateTimeFormats() throws IOException { knownLocaledPatternList.clear();//from ww w . ja v a 2 s . c o m knownPatternList.clear(); processBaseTimePatternsByLocales(); int basePatternCount = knownLocaledPatternList.size(); if (PRINT_DETAILED_RESULTS) { System.out.println("\n#Total = " + knownLocaledPatternList.size() + // " (#baseDatePatterns = " + basePatternCount + ")\n");// } // table header timeSampleFileTextBuilder.append("Sample\tPattern\tLocale\tFormatStyle\tIsWithTime\n"); RegexGenerator regexGenerator = new RegexGenerator(); for (LocaledPattern lp : knownLocaledPatternList) { timePatternFileTextBuilder.append(lp).append("\n"); String regex = regexGenerator.convertPatternToRegex(lp.pattern); timeRegexFileTextBuilder.append(lp.getPattern()).append("\t^").append(regex).append("$\n"); timeSampleFileTextBuilder .append(ZONED_DATE_TIME.format(DateTimeFormatter.ofPattern(lp.getPattern(), lp.getLocale()))) .append("\t").append(lp.getPattern())// .append("\t").append(lp.getLocale())// .append("\t").append(lp.getFormatStyle())// .append("\t").append(lp.isWithTime()).append("\n"); } // Time Formats String path = SystemDateTimePatternManager.class.getResource("TimeFormats.txt").getFile().replace( "target" + File.separator + "classes", "src" + File.separator + "main" + File.separator + "resources"); IOUtils.write(timePatternFileTextBuilder.toString(), new FileOutputStream(new File(path))); // Time Regexes path = SystemDateTimePatternManager.class.getResource("TimeRegexes.txt").getFile().replace( "target" + File.separator + "classes", "src" + File.separator + "main" + File.separator + "resources"); IOUtils.write(timeRegexFileTextBuilder.toString(), new FileOutputStream(new File(path))); // Time Samples path = SystemDateTimePatternManager.class.getResource("TimeSampleTable.txt").getFile().replace( "target" + File.separator + "classes", "src" + File.separator + "test" + File.separator + "resources"); IOUtils.write(timeSampleFileTextBuilder.toString(), new FileOutputStream(new File(path))); }
From source file:investiagenofx2.view.InvestiaGenOFXController.java
private void getAccountsInvestmentsFromWeb() { @SuppressWarnings(("unchecked")) List<HtmlTable> tables = (List<HtmlTable>) htmlPage .getByXPath("//table[contains(@class, 'table-striped')]"); @SuppressWarnings(("unchecked")) List<HtmlDivision> divBalancesAs = (List<HtmlDivision>) htmlPage .getByXPath("//div[contains(text(),'Soldes au')]"); LocalDate balancesAs = LocalDate.parse(divBalancesAs.get(0).asText().replace("Soldes au ", ""), DateTimeFormatter.ofPattern("dd MMMM yyyy", Locale.CANADA_FRENCH)); int i = 0;//from w w w .j a v a2 s. c o m for (HtmlTable table : tables) { if (!table.asText().contains("Numro de \r\n compte")) { continue; } if (accounts.get(i).getAccountID() == null) { accounts.get(i).setAccountID(table.getCellAt(1, 3).getTextContent()); } Float total = 0f; for (int j = 1; j < table.getRowCount(); j++) { String symbol = table.getCellAt(j, 1).getTextContent(); String name = table.getCellAt(j, 0).getTextContent(); String quantity = table.getCellAt(j, 5).getTextContent().replaceAll("[^0-9,]", "").replace(",", "."); String lastPrice = table.getCellAt(j, 6).getTextContent().replaceAll("[^0-9,]", "").replace(",", "."); String marketValue = table.getCellAt(j, 7).getTextContent().replaceAll("[^0-9,]", "").replace(",", "."); Investment investment = new Investment(symbol, name, quantity, lastPrice, marketValue); accounts.get(i).add(investment); total += Float.valueOf(marketValue); } String totalString = String.format("%.02f", total); Investment investment = new Investment("", "Total", totalString, "1.00", totalString); accounts.get(i).add(investment); if (!balancesAs.equals(dataAsDate)) accounts.get(i).setBalanceDate(balancesAs); i++; } if (!balancesAs.equals(dataAsDate)) dataAsDate = balancesAs; }