List of usage examples for java.time LocalDateTime ofInstant
public static LocalDateTime ofInstant(Instant instant, ZoneId zone)
From source file:com.hengyi.japp.tools.DateTimeUtil.java
public static LocalDateTime toLocalDateTime(Date date) { return date == null ? null : LocalDateTime.ofInstant(date.toInstant(), ZoneId.systemDefault()); }
From source file:Main.java
public static String getStringFromMillis(final Number millis) { return FORMATTER .format(LocalDateTime.ofInstant(Instant.ofEpochMilli(millis.longValue()), ZoneId.systemDefault())); }
From source file:com.opinionlab.woa.Awesome.java
public Awesome(Message message) { try {/* www . ja v a2 s.c o m*/ this.messageID = ((MimeMessage) message).getMessageID(); this.id = ID_PTN.matcher(this.messageID).replaceAll("_"); this.receivedDate = message.getReceivedDate(); this.monthDay = DATE_FORMATTER .format(LocalDateTime.ofInstant(receivedDate.toInstant(), systemDefault())); this.to = new Person((InternetAddress) //todo Do this smarter message.getRecipients(Message.RecipientType.TO)[0]); this.from = new Person((InternetAddress) message.getFrom()[0]); this.subject = message.getSubject(); final MimeMessageParser parser = new MimeMessageParser((MimeMessage) message).parse(); if (!parser.hasPlainContent()) { LOGGER.error(format("Unable to parse message '%s'; has no plain content", this.messageID)); this.comment = "Unknown content."; } else { this.comment = parseContent(parser.getPlainContent()); } } catch (Throwable t) { throw new IllegalArgumentException(t); } }
From source file:no.imr.stox.functions.acoustic.PgNapesIO.java
public static void export2(String cruise, String country, String callSignal, String path, String fileName, List<DistanceBO> distances, Double groupThickness, Integer freqFilter, String specFilter, boolean withZeros) { Set<Integer> freqs = distances.stream().flatMap(dist -> dist.getFrequencies().stream()) .map(FrequencyBO::getFreq).collect(Collectors.toSet()); if (freqFilter == null && freqs.size() == 1) { freqFilter = freqs.iterator().next(); }/*w w w . j av a 2 s. co m*/ if (freqFilter == null) { System.out.println("Multiple frequencies, specify frequency filter as parameter"); return; } Integer freqFilterF = freqFilter; // ef.final List<String> acList = distances.parallelStream().flatMap(dist -> dist.getFrequencies().stream()) .filter(fr -> freqFilterF.equals(fr.getFreq())).map(f -> { DistanceBO d = f.getDistanceBO(); LocalDateTime sdt = LocalDateTime.ofInstant(d.getStart_time().toInstant(), ZoneOffset.UTC); Double intDist = d.getIntegrator_dist(); String month = StringUtils.leftPad(sdt.getMonthValue() + "", 2, "0"); String day = StringUtils.leftPad(sdt.getDayOfMonth() + "", 2, "0"); String hour = StringUtils.leftPad(sdt.getHour() + "", 2, "0"); String minute = StringUtils.leftPad(sdt.getMinute() + "", 2, "0"); String log = Conversion.formatDoubletoDecimalString(d.getLog_start(), "0.0"); String acLat = Conversion.formatDoubletoDecimalString(d.getLat_start(), "0.000"); String acLon = Conversion.formatDoubletoDecimalString(d.getLon_start(), "0.000"); return Stream .of(d.getNation(), d.getPlatform(), d.getCruise(), log, sdt.getYear(), month, day, hour, minute, acLat, acLon, intDist, f.getFreq(), f.getThreshold()) .map(o -> o == null ? "" : o.toString()).collect(Collectors.joining("\t")) + "\t"; }).collect(Collectors.toList()); String fil1 = path + "/" + fileName + ".txt"; acList.add(0, Stream.of("Country", "Vessel", "Cruise", "Log", "Year", "Month", "Day", "Hour", "Min", "AcLat", "AcLon", "Logint", "Frequency", "Sv_threshold").collect(Collectors.joining("\t"))); try { Files.write(Paths.get(fil1), acList, StandardOpenOption.CREATE, StandardOpenOption.TRUNCATE_EXISTING); } catch (IOException ex) { Logger.getLogger(PgNapesIO.class.getName()).log(Level.SEVERE, null, ex); } acList.clear(); // Acoustic values distances.stream().filter(d -> d.getPel_ch_thickness() != null) .flatMap(dist -> dist.getFrequencies().stream()).filter(fr -> freqFilterF.equals(fr.getFreq())) .forEachOrdered(f -> { try { Double groupThicknessF = Math.max(f.getDistanceBO().getPel_ch_thickness(), groupThickness); Map<String, Map<Integer, Double>> pivot = f.getSa().stream() .filter(s -> s.getCh_type().equals("P")).map(s -> new SAGroup(s, groupThicknessF)) .filter(s -> s.getSpecies() != null && (specFilter == null || specFilter.equals(s.getSpecies()))) // create pivot table: species (dim1) -> depth interval index (dim2) -> sum sa (group aggregator) .collect(Collectors.groupingBy(SAGroup::getSpecies, Collectors.groupingBy( SAGroup::getDepthGroupIdx, Collectors.summingDouble(SAGroup::sa)))); if (pivot.isEmpty() && specFilter != null && withZeros) { pivot.put(specFilter, new HashMap<>()); } Integer maxGroupIdx = pivot.entrySet().stream().flatMap(e -> e.getValue().keySet().stream()) .max(Integer::compare).orElse(null); if (maxGroupIdx == null) { return; } acList.addAll(pivot.entrySet().stream().sorted(Comparator.comparing(Map.Entry::getKey)) .flatMap(e -> { return IntStream.range(0, maxGroupIdx + 1).boxed().map(groupIdx -> { Double chUpDepth = groupIdx * groupThicknessF; Double chLowDepth = (groupIdx + 1) * groupThicknessF; Double sa = e.getValue().get(groupIdx); if (sa == null) { sa = 0d; } String res = null; if (withZeros || sa > 0d) { DistanceBO d = f.getDistanceBO(); String log = Conversion.formatDoubletoDecimalString(d.getLog_start(), "0.0"); LocalDateTime sdt = LocalDateTime .ofInstant(d.getStart_time().toInstant(), ZoneOffset.UTC); String month = StringUtils.leftPad(sdt.getMonthValue() + "", 2, "0"); String day = StringUtils.leftPad(sdt.getDayOfMonth() + "", 2, "0"); //String sas = String.format(Locale.UK, "%11.5f", sa); res = Stream .of(d.getNation(), d.getPlatform(), d.getCruise(), log, sdt.getYear(), month, day, e.getKey(), chUpDepth, chLowDepth, sa) .map(o -> o == null ? "" : o.toString()) .collect(Collectors.joining("\t")); } return res; }).filter(s -> s != null); }).collect(Collectors.toList())); } catch (Exception e) { e.printStackTrace(); } }); String fil2 = path + "/" + fileName + "Values.txt"; acList.add(0, Stream.of("Country", "Vessel", "Cruise", "Log", "Year", "Month", "Day", "Species", "ChUppDepth", "ChLowDepth", "SA").collect(Collectors.joining("\t"))); try { Files.write(Paths.get(fil2), acList, StandardOpenOption.CREATE, StandardOpenOption.TRUNCATE_EXISTING); } catch (IOException ex) { Logger.getLogger(PgNapesIO.class.getName()).log(Level.SEVERE, null, ex); } }
From source file:be.wegenenverkeer.common.resteasy.json.Iso8601AndOthersLocalDateTimeFormat.java
/** * Parse string to date.// w w w . ja v a 2s. c o m * * @param str string to parse * @return date */ public LocalDateTime parse(String str) { LocalDateTime date = null; if (StringUtils.isNotBlank(str)) { // try full ISO 8601 format first try { Date timestamp = ISO8601Utils.parse(str, new ParsePosition(0)); Instant instant = Instant.ofEpochMilli(timestamp.getTime()); return LocalDateTime.ofInstant(instant, ZoneId.systemDefault()); } catch (IllegalArgumentException | ParseException ex) { // ignore, try next format date = null; // dummy } // then try ISO 8601 format without timezone try { return LocalDateTime.from(iso8601NozoneFormat.parse(str)); } catch (IllegalArgumentException | DateTimeParseException ex) { // ignore, try next format date = null; // dummy } // then try a list of formats for (DateTimeFormatter formatter : FORMATS) { try { TemporalAccessor ta = formatter.parse(str); try { return LocalDateTime.from(ta); } catch (DateTimeException dte) { return LocalDate.from(ta).atStartOfDay(); } } catch (IllegalArgumentException | DateTimeParseException e) { // ignore, try next format date = null; // dummy } } throw new IllegalArgumentException("Could not parse date " + str + " using ISO 8601 or any of the formats " + Arrays.asList(FORMATS) + "."); } return date; // empty string }
From source file:at.becast.youploader.youtube.GuiUploadEvent.java
@Override public void onInit() { this.starttime = System.currentTimeMillis(); this.lastdata = 0; this.lasttime = this.starttime; this.lastdb = this.starttime; Date in = new Date(this.starttime); LocalDateTime ldt = LocalDateTime.ofInstant(in.toInstant(), ZoneId.systemDefault()); Date out = Date.from(ldt.atZone(ZoneId.systemDefault()).toInstant()); DateFormat formatter = DateFormat.getDateTimeInstance(DateFormat.SHORT, DateFormat.SHORT, Locale.getDefault()); frame.getlblStart().setText(formatter.format(out)); frame.getProgressBar().setString("0,00 %"); frame.getProgressBar().setValue(0);//from w w w . j a v a 2 s . c o m frame.getProgressBar().revalidate(); frame.getBtnCancel().setEnabled(true); frame.getBtnEdit().setEnabled(true); frame.getBtnDelete().setEnabled(false); frame.revalidate(); frame.repaint(); }
From source file:Jimbo.Cheerlights.MQTTListener.java
/** * Receive an MQTT message./*from www . j a v a2s . c o m*/ * * @param topic The topic it's on * @param message The message itself */ @Override public void receive(String topic, String message) { try { JSONObject j = new JSONObject(message); final Instant instant = Instant.ofEpochMilli(j.getLong("sent")).truncatedTo(ChronoUnit.SECONDS); final LocalDateTime stamp = LocalDateTime.ofInstant(instant, ZONE); final String when = stamp.format(DateTimeFormatter.ISO_LOCAL_DATE_TIME); LOG.log(Level.INFO, "{0} (@{1}) sent {2}: {3}", new Object[] { j.getString("name"), j.getString("screen"), when, j.getString("text") }); target.update(j.getInt("colour")); } catch (JSONException | IOException e) { LOG.log(Level.WARNING, "Unable to parse: \"{0}\": {1}", new Object[] { message, e.getLocalizedMessage() }); } }
From source file:it.tidalwave.accounting.importer.ibiz.impl.ConfigurationDecorator.java
@Nonnull public LocalDateTime getDateTime(final @Nonnull String key) { return LocalDateTime.ofInstant(((Date) delegate.getProperty(key)).toInstant(), ZoneId.systemDefault()); }
From source file:com.otway.picasasync.syncutil.ImageSync.java
public boolean newerThan(LocalDateTime threshold) throws ServiceException { boolean localFileExists = localFile.exists(); if (localFileExists) { LocalDateTime localTimeStamp = getTimeFromMS(localFile.lastModified()); // There's a local file. See if it's newer if (localTimeStamp.isAfter(threshold)) return true; }// www. java2 s .co m if (remotePhoto != null) { LocalDateTime remoteTimeStamp = LocalDateTime.ofInstant(remotePhoto.getTimestamp().toInstant(), ZoneId.systemDefault()); // There's a remote file. See if it's newer if (remoteTimeStamp.isAfter(threshold)) return true; } return false; }
From source file:org.ops4j.pax.web.resources.extender.internal.IndexedOsgiResourceLocator.java
@Override public void register(final Bundle bundle) { Collection<URL> urls; try {//from w ww . jav a 2 s . c om urls = Collections.list(bundle.findEntries(RESOURCE_ROOT, "*.*", true)); } catch (IllegalStateException e) { logger.error("Error retrieving bundle-resources from bundle '{}'", bundle.getSymbolicName(), e); urls = Collections.emptyList(); } urls.forEach( url -> index.addResourceToIndex(url.getPath(), new ResourceInfo(url, LocalDateTime .ofInstant(Instant.ofEpochMilli(bundle.getLastModified()), ZoneId.systemDefault()), bundle.getBundleId()), bundle)); logger.info("Bundle '{}' scanned for resources in '{}': {} entries added to index.", new Object[] { bundle.getSymbolicName(), RESOURCE_ROOT, urls.size() }); }