Example usage for java.time ZonedDateTime format

List of usage examples for java.time ZonedDateTime format

Introduction

In this page you can find the example usage for java.time ZonedDateTime format.

Prototype

@Override 
public String format(DateTimeFormatter formatter) 

Source Link

Document

Formats this date-time using the specified formatter.

Usage

From source file:dk.dma.vessel.track.store.AisStoreClient.java

public List<PastTrackPos> getPastTrack(int mmsi, Integer minDist, Duration age) {

    // Determine URL
    age = age != null ? age : Duration.parse(pastTrackTtl);
    minDist = minDist == null ? Integer.valueOf(pastTrackMinDist) : minDist;
    ZonedDateTime now = ZonedDateTime.now();
    String from = now.format(DateTimeFormatter.ISO_INSTANT);
    ZonedDateTime end = now.minus(age);
    String to = end.format(DateTimeFormatter.ISO_INSTANT);
    String interval = String.format("%s/%s", to, from);
    String url = String.format("%s?mmsi=%d&interval=%s", aisViewUrl, mmsi, interval);

    final List<PastTrackPos> track = new ArrayList<>();
    try {//from w  ww . j  a va 2 s .co  m
        long t0 = System.currentTimeMillis();

        // TEST
        url = url + "&filter=" + URLEncoder.encode("(s.country not in (GBR)) & (s.region!=808)", "UTF-8");

        // Set up a few timeouts and fetch the attachment
        URLConnection con = new URL(url).openConnection();
        con.setConnectTimeout(10 * 1000); // 10 seconds
        con.setReadTimeout(60 * 1000); // 1 minute

        if (!StringUtils.isEmpty(aisAuthHeader)) {
            con.setRequestProperty("Authorization", aisAuthHeader);
        }

        try (InputStream in = con.getInputStream(); BufferedInputStream bin = new BufferedInputStream(in)) {
            AisReader aisReader = AisReaders.createReaderFromInputStream(bin);
            aisReader.registerPacketHandler(new Consumer<AisPacket>() {
                @Override
                public void accept(AisPacket p) {
                    AisMessage message = p.tryGetAisMessage();
                    if (message == null || !(message instanceof IVesselPositionMessage)) {
                        return;
                    }
                    VesselTarget target = new VesselTarget();
                    target.merge(p, message);
                    if (!target.checkValidPos()) {
                        return;
                    }
                    track.add(new PastTrackPos(target.getLat(), target.getLon(), target.getCog(),
                            target.getSog(), target.getLastPosReport()));
                }
            });
            aisReader.start();
            try {
                aisReader.join();
            } catch (InterruptedException e) {
                return null;
            }
        }
        LOG.info(String.format("Read %d past track positions in %d ms", track.size(),
                System.currentTimeMillis() - t0));
    } catch (IOException e) {
        LOG.error("Failed to make REST query: " + url);
        throw new InternalError("REST endpoint failed");
    }
    LOG.info("AisStore returned track with " + track.size() + " points");
    return PastTrack.downSample(track, minDist, age.toMillis());
}

From source file:de.rkl.tools.tzconv.TimezoneConverter.java

private String formatOriginalDate(final ZonedDateTime dateTime) {
    return dateTime.format(dateFormatter);
}

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:com.github.ibm.domino.client.BaseClient.java

protected String getDateParameter(ZonedDateTime value) {
    StringBuilder sValue = new StringBuilder(value.format(DateTimeFormatter.ISO_DATE_TIME));
    int i = sValue.indexOf(GMT_STRING);
    if (i >= 0) {
        sValue.delete(i, i + GMT_STRING.length());
    }/*  www . java  2 s .c o  m*/
    i = sValue.indexOf(PERIOD);
    if (i >= 0) {
        sValue.delete(i, i + 4);
    }
    return sValue.toString();
}

From source file:com.match_tracker.twitter.TwitterSearch.java

public String constructSearchQuery(String queryString, ZonedDateTime startTime, ZonedDateTime endTime) {
    DateTimeFormatter ISO_Datetime = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ssX");
    return queryString + " " + "posted:" + startTime.format(ISO_Datetime) + "," + endTime.format(ISO_Datetime);
}

From source file:org.bedework.synch.cnctrs.orgSyncV2.OrgSyncV2ConnectorInstance.java

private IcalendarType toXcal(final List<OrgSyncV2Event> osEvents, final boolean onlyPublic) {
    final IcalendarType ical = new IcalendarType();
    final VcalendarType vcal = new VcalendarType();

    ical.getVcalendar().add(vcal);//from w  ww  .  jav  a2 s.  com

    vcal.setProperties(new ArrayOfProperties());
    final List<JAXBElement<? extends BasePropertyType>> vcalProps = vcal.getProperties()
            .getBasePropertyOrTzid();

    final VersionPropType vers = new VersionPropType();
    vers.setText("2.0");
    vcalProps.add(of.createVersion(vers));

    final ProdidPropType prod = new ProdidPropType();
    prod.setText("//Bedework.org//BedeWork V3.11.1//EN");
    vcalProps.add(of.createProdid(prod));

    final ArrayOfComponents aoc = new ArrayOfComponents();
    vcal.setComponents(aoc);

    for (final OrgSyncV2Event osev : osEvents) {
        if (onlyPublic && !osev.getIsPublic()) {
            continue;
        }

        final VeventType ev = new VeventType();

        aoc.getBaseComponent().add(of.createVevent(ev));

        ev.setProperties(new ArrayOfProperties());
        final List<JAXBElement<? extends BasePropertyType>> evProps = ev.getProperties()
                .getBasePropertyOrTzid();

        final UidPropType uid = new UidPropType();
        uid.setText(config.getUidPrefix() + "-" + osev.getId());
        evProps.add(of.createUid(uid));

        final DtstampPropType dtstamp = new DtstampPropType();
        try {
            //Get todays date
            final ZonedDateTime today = ZonedDateTime.now(ZoneOffset.UTC);
            final String todayStr = today.format(DateTimeFormatter.ISO_INSTANT);

            dtstamp.setUtcDateTime(XcalUtil.getXMlUTCCal(todayStr));
            evProps.add(of.createDtstamp(dtstamp));

            final CreatedPropType created = new CreatedPropType();
            created.setUtcDateTime(XcalUtil.getXMlUTCCal(todayStr));
            evProps.add(of.createCreated(created));

            final SummaryPropType sum = new SummaryPropType();
            sum.setText(osev.getName());
            evProps.add(of.createSummary(sum));

            final DescriptionPropType desc = new DescriptionPropType();
            desc.setText(osev.getDescription());
            evProps.add(of.createDescription(desc));

            final LocationPropType l = new LocationPropType();
            l.setText(osev.getLocation());
            evProps.add(of.createLocation(l));

            if (info.getLocationKey() != null) {
                final XBedeworkLocKeyParamType par = of.createXBedeworkLocKeyParamType();

                par.setText(info.getLocationKey());
                l.setParameters(new ArrayOfParameters());
                l.getParameters().getBaseParameter().add(of.createXBedeworkLocKey(par));
            }
        } catch (final Throwable t) {
            error(t);
            continue;
        }

        if (osev.getCategory() != null) {
            final CategoriesPropType cat = new CategoriesPropType();
            cat.getText().add(osev.getCategory().getName());
            evProps.add(of.createCategories(cat));
        }

        /* The first (only) element of occurrences is the start/end of the
           event or master.
                
           If there are more occurrences these become rdates and the event is
           recurring.
         */

        if (Util.isEmpty(osev.getOccurrences())) {
            // warn?
            continue;
        }

        boolean first = true;
        for (final OrgSyncV2Occurrence occ : osev.getOccurrences()) {
            if (first) {
                final DtstartPropType dtstart = (DtstartPropType) makeDt(new DtstartPropType(),
                        occ.getStartsAt());
                evProps.add(of.createDtstart(dtstart));

                final DtendPropType dtend = (DtendPropType) makeDt(new DtendPropType(), occ.getEndsAt());
                evProps.add(of.createDtend(dtend));

                first = false;
                continue;
            }

            // Add an rdate
            // TODO - add duration if different from the master
            final RdatePropType rdate = (RdatePropType) makeDt(new RdatePropType(), occ.getStartsAt());
            evProps.add(of.createRdate(rdate));
        }
    }

    return ical;
}

From source file:de.swm.nis.logicaldecoding.tracktable.TrackTablePublisher.java

private PGobject getTimestamp(DmlEvent event) {
    PGobject timestamp = new PGobject();
    timestamp.setType("timestamp");
    try {/*from   w  w  w.j av  a 2s  .co m*/
        ZonedDateTime time = event.getCommitTime();
        if (time == null) {
            timestamp.setValue("1970-01-01T00:00:00+00:00");
            return timestamp;
        }
        timestamp.setValue(time.format(DateTimeFormatter.ISO_OFFSET_DATE_TIME));
    } catch (SQLException e) {
        log.error("Error while setting Timestamp SQL PGobject type:", e);
    }
    return timestamp;
}

From source file:com.streamsets.datacollector.json.TestJsonRecordWriterImpl.java

@Test
public void testZonedDateTime() throws Exception {
    ZonedDateTime now = ZonedDateTime.now();
    StringWriter writer = new StringWriter();
    JsonRecordWriterImpl jsonRecordWriter = new JsonRecordWriterImpl(writer, Mode.MULTIPLE_OBJECTS);

    Record record = new RecordImpl("stage", "id", null, null);
    record.set(Field.createZonedDateTime(now));
    jsonRecordWriter.write(record);//from  w w w. j  a  v  a2  s.com
    jsonRecordWriter.close();

    Assert.assertEquals("\"" + now.format(DateTimeFormatter.ISO_ZONED_DATE_TIME) + "\"", writer.toString());
}

From source file:it.tidalwave.northernwind.frontend.ui.component.blog.htmltemplate.HtmlTemplateBlogViewController.java

/*******************************************************************************************************************
 *
 * Renders the date of the blog post.// w  w w .ja va 2s .c  o  m
 *
 ******************************************************************************************************************/
/* package */ void renderDate(final @Nonnull StringBuilder htmlBuilder,
        final @Nonnull ZonedDateTime blogDateTime) {
    htmlBuilder.append(String.format("<span class='nw-publishDate'>%s</span>%n",
            blogDateTime.format(getDateTimeFormatter())));
}