Example usage for java.time LocalDateTime getHour

List of usage examples for java.time LocalDateTime getHour

Introduction

In this page you can find the example usage for java.time LocalDateTime getHour.

Prototype

public int getHour() 

Source Link

Document

Gets the hour-of-day field.

Usage

From source file:edu.unibonn.kmeans.mapreduce.plotting.TimeSeriesPlotter_KMeans.java

private XYDataset createDataset(ArrayList<Sensor> sensors) {
    final TimeSeriesCollection dataset = new TimeSeriesCollection();

    for (int i = 0; i < sensors.size(); i++)
    //for (int i = 0; i < 100; i++)
    {//from  ww w .  j ava2s  .com
        Sensor current_sensor = sensors.get(i);
        ArrayList<Measurement> current_measurements = current_sensor.getMeasurements();

        final TimeSeries s1 = new TimeSeries("Sensor " + i, Hour.class);

        for (int j = 0; j < current_measurements.size(); j++) {
            Measurement current_measurement = current_measurements.get(j);

            LocalDateTime current_time = current_measurement.getRecord_time();

            s1.add(new Hour(current_time.getHour(), current_time.getDayOfMonth(), current_time.getMonthValue(),
                    current_time.getYear()), current_measurement.getErlang());
        }

        dataset.addSeries(s1);
    }

    dataset.setDomainIsPointsInTime(true);

    return dataset;
}

From source file:dk.dma.ais.packet.AisPacketCSVOutputSink.java

protected String formatEta(Date eta) {
    LocalDateTime time = LocalDateTime.ofInstant(Instant.ofEpochMilli(eta.getTime()), ZoneId.systemDefault());
    return formatEta(time.getDayOfMonth(), time.getMonthValue(), time.getHour(), time.getMinute());
}

From source file:org.apache.openmeetings.web.user.calendar.CalendarPanel.java

@Override
protected void onInitialize() {
    final Form<Date> form = new Form<>("form");
    add(form);//from w ww  .j  a  v a  2 s  .  c o  m

    dialog = new AppointmentDialog("appointment", this, new CompoundPropertyModel<>(getDefault()));
    add(dialog);

    boolean isRtl = isRtl();
    Options options = new Options();
    options.set("isRTL", isRtl);
    options.set("height", Options.asString("parent"));
    options.set("header", isRtl
            ? "{left: 'agendaDay,agendaWeek,month', center: 'title', right: 'today nextYear,next,prev,prevYear'}"
            : "{left: 'prevYear,prev,next,nextYear today', center: 'title', right: 'month,agendaWeek,agendaDay'}");
    options.set("allDaySlot", false);
    options.set("axisFormat", Options.asString("H(:mm)"));
    options.set("defaultEventMinutes", 60);
    options.set("timeFormat", Options.asString("H(:mm)"));

    options.set("buttonText", new JSONObject().put("month", getString("801")).put("week", getString("800"))
            .put("day", getString("799")).put("today", getString("1555")).toString());

    options.set("locale", Options.asString(WebSession.get().getLocale().toLanguageTag()));

    calendar = new Calendar("calendar", new AppointmentModel(), options) {
        private static final long serialVersionUID = 1L;

        @Override
        protected void onInitialize() {
            super.onInitialize();
            add(new CalendarFunctionsBehavior(getMarkupId()));
        }

        @Override
        public boolean isSelectable() {
            return true;
        }

        @Override
        public boolean isDayClickEnabled() {
            return true;
        }

        @Override
        public boolean isEventClickEnabled() {
            return true;
        }

        @Override
        public boolean isEventDropEnabled() {
            return true;
        }

        @Override
        public boolean isEventResizeEnabled() {
            return true;
        }

        //no need to override onDayClick
        @Override
        public void onSelect(AjaxRequestTarget target, CalendarView view, LocalDateTime start,
                LocalDateTime end, boolean allDay) {
            Appointment a = getDefault();
            LocalDateTime s = start, e = end;
            if (CalendarView.month == view) {
                LocalDateTime now = ZonedDateTime.now(getZoneId()).toLocalDateTime();
                s = start.withHour(now.getHour()).withMinute(now.getMinute());
                e = s.plus(1, ChronoUnit.HOURS);
            }
            a.setStart(getDate(s));
            a.setEnd(getDate(e));
            dialog.setModelObjectWithAjaxTarget(a, target);

            dialog.open(target);
        }

        @Override
        public void onEventClick(AjaxRequestTarget target, CalendarView view, String eventId) {
            if (!StringUtils.isNumeric(eventId)) {
                return;
            }
            Appointment a = apptDao.get(Long.valueOf(eventId));
            dialog.setModelObjectWithAjaxTarget(a, target);

            dialog.open(target);
        }

        @Override
        public void onEventDrop(AjaxRequestTarget target, String eventId, long delta, boolean allDay) {
            if (!StringUtils.isNumeric(eventId)) {
                refresh(target);
                return;
            }
            Appointment a = apptDao.get(Long.valueOf(eventId));
            if (!AppointmentDialog.isOwner(a)) {
                return;
            }
            java.util.Calendar cal = WebSession.getCalendar();
            cal.setTime(a.getStart());
            cal.add(java.util.Calendar.MILLISECOND, (int) delta);
            a.setStart(cal.getTime());

            cal.setTime(a.getEnd());
            cal.add(java.util.Calendar.MILLISECOND, (int) delta);
            a.setEnd(cal.getTime());

            apptDao.update(a, getUserId());

            if (a.getCalendar() != null) {
                updatedeleteAppointment(target, CalendarDialog.DIALOG_TYPE.UPDATE_APPOINTMENT, a);
            }
        }

        @Override
        public void onEventResize(AjaxRequestTarget target, String eventId, long delta) {
            if (!StringUtils.isNumeric(eventId)) {
                refresh(target);
                return;
            }
            Appointment a = apptDao.get(Long.valueOf(eventId));
            if (!AppointmentDialog.isOwner(a)) {
                return;
            }
            java.util.Calendar cal = WebSession.getCalendar();
            cal.setTime(a.getEnd());
            cal.add(java.util.Calendar.MILLISECOND, (int) delta);
            a.setEnd(cal.getTime());

            apptDao.update(a, getUserId());

            if (a.getCalendar() != null) {
                updatedeleteAppointment(target, CalendarDialog.DIALOG_TYPE.UPDATE_APPOINTMENT, a);
            }
        }
    };

    form.add(calendar);

    populateGoogleCalendars();

    add(refreshTimer);
    add(syncTimer);

    calendarDialog = new CalendarDialog("calendarDialog", this,
            new CompoundPropertyModel<>(getDefaultCalendar()));

    add(calendarDialog);

    calendarListContainer.setOutputMarkupId(true);
    calendarListContainer
            .add(new ListView<OmCalendar>("items", new LoadableDetachableModel<List<OmCalendar>>() {
                private static final long serialVersionUID = 1L;

                @Override
                protected List<OmCalendar> load() {
                    List<OmCalendar> cals = new ArrayList<>(apptManager.getCalendars(getUserId()));
                    cals.addAll(apptManager.getGoogleCalendars(getUserId()));
                    return cals;
                }
            }) {
                private static final long serialVersionUID = 1L;

                @Override
                protected void populateItem(final ListItem<OmCalendar> item) {
                    item.setOutputMarkupId(true);
                    final OmCalendar cal = item.getModelObject();
                    item.add(new WebMarkupContainer("item").add(new Label("name", cal.getTitle())));
                    item.add(new AjaxEventBehavior(EVT_CLICK) {
                        private static final long serialVersionUID = 1L;

                        @Override
                        protected void onEvent(AjaxRequestTarget target) {
                            calendarDialog.open(target, CalendarDialog.DIALOG_TYPE.UPDATE_CALENDAR, cal);
                            target.add(calendarDialog);
                        }
                    });
                }
            });

    add(new Button("syncCalendarButton").add(new AjaxEventBehavior(EVT_CLICK) {
        private static final long serialVersionUID = 1L;

        @Override
        protected void onEvent(AjaxRequestTarget target) {
            syncCalendar(target);
        }
    }));

    add(new Button("submitCalendar").add(new AjaxEventBehavior(EVT_CLICK) {
        private static final long serialVersionUID = 1L;

        @Override
        protected void onEvent(AjaxRequestTarget target) {
            calendarDialog.open(target, CalendarDialog.DIALOG_TYPE.UPDATE_CALENDAR, getDefaultCalendar());
            target.add(calendarDialog);
        }
    }));

    add(calendarListContainer);

    super.onInitialize();
}

From source file:msi.gama.util.GamaDate.java

public IList<?> listValue(final IScope scope, final IType<?> ct) {
    final LocalDateTime ld = LocalDateTime.from(internal);
    return GamaListFactory.create(scope, ct, ld.getYear(), ld.getMonthValue(), ld.getDayOfWeek().getValue(),
            ld.getHour(), ld.getMinute(), ld.getSecond());
}

From source file:com.bdb.weather.display.day.DayPressurePane.java

@Override
protected void addAnnotations(XYPlot plot, SummaryRecord summaryRecord) {
    plot.getRenderer(0).removeAnnotations();
    plot.getRenderer(1).removeAnnotations();

    if (summaryRecord == null)
        return;//from w ww .j  av a 2 s .  com

    LocalDateTime maxTime = summaryRecord.getMaxBaroPressureTime();
    Pressure maxBaroPressure = summaryRecord.getMaxBaroPressure();
    LocalDateTime minTime = summaryRecord.getMinBaroPressureTime();
    Pressure minBaroPressure = summaryRecord.getMinBaroPressure();

    //
    // Barometric pressure
    //
    String highAnnotation = maxBaroPressure.toString() + Pressure.getDefaultUnit() + " "
            + DisplayConstants.formatTime(maxTime.toLocalTime());
    String lowAnnotation = minBaroPressure.toString() + Pressure.getDefaultUnit() + " "
            + DisplayConstants.formatTime(minTime.toLocalTime());

    XYTextAnnotation a = new XYTextAnnotation(highAnnotation,
            (double) TimeUtils.localDateTimeToEpochMillis(maxTime), maxBaroPressure.get());
    a.setTextAnchor(TextAnchor.BASELINE_CENTER);

    plot.getRenderer(0).addAnnotation(a);

    TextAnchor anchor = TextAnchor.TOP_CENTER;

    if (minTime.getHour() <= 2)
        anchor = TextAnchor.TOP_LEFT;
    else if (minTime.getHour() >= 22)
        anchor = TextAnchor.TOP_RIGHT;

    a = new XYTextAnnotation(lowAnnotation, (double) TimeUtils.localDateTimeToEpochMillis(minTime),
            minBaroPressure.get());
    a.setTextAnchor(anchor);

    plot.getRenderer(0).addAnnotation(a);

    SolarRadiation maxSolarRadiation = summaryRecord.getMaxSolarRadiation();
    maxTime = summaryRecord.getMaxSolarRadiationTime();

    if (maxSolarRadiation != null) {
        highAnnotation = maxSolarRadiation.toString() + SolarRadiation.Unit.WATTS_PER_METER_SQUARED + " "
                + DisplayConstants.formatTime(maxTime.toLocalTime());
        a = new XYTextAnnotation(highAnnotation, (double) TimeUtils.localDateTimeToEpochMillis(maxTime),
                maxSolarRadiation.get());
        a.setTextAnchor(TextAnchor.BASELINE_CENTER);
        plot.getRenderer(1).addAnnotation(a);
    }
}

From source file:com.snowy.data.java

public HashMap<Integer, String> chatsSince(int id, int lastMessageid) {
    HashMap<Integer, String> hm = new HashMap<>();
    try {//from   w w w  . j a v  a2  s.c  o m
        PreparedStatement ps = con.prepareStatement(
                "select Timestamp,Message,sender,Message_id from chat where GameId =? and Message_id > ?");
        ps.setInt(1, id);
        ps.setInt(2, lastMessageid);
        ResultSet rs = ps.executeQuery();
        rs.beforeFirst();
        while (rs.next()) {
            LocalDateTime t = rs.getTimestamp("Timestamp").toLocalDateTime();
            String time = String.format("%02d:%02d", t.getHour(), t.getMinute());
            hm.put(rs.getInt("Message_id"),
                    time + " " + rs.getString("sender") + ": " + rs.getString("Message") + "\n");
        }
        //ps.close();
        //rs.close();
    } catch (SQLException ex) {
        Logger.getLogger(data.class.getName()).log(Level.SEVERE, null, ex);
    }
    return hm;
}

From source file:com.objy.se.ClassAccessor.java

public Object getCorrectValue(String strValue, LogicalType logicalType) {
    Object retValue = null;/*w w w.j  av  a  2 s.c o  m*/
    switch (logicalType) {
    case INTEGER: {
        long attrValue = 0;
        try {
            if (!strValue.equals("")) {
                attrValue = Long.parseLong(strValue);
            }
        } catch (NumberFormatException nfEx) {
            //        System.out.println("... entry: " + entry.getValue() + " for raw: " + entry.getKey());
            nfEx.printStackTrace();
            throw nfEx;
        }
        retValue = Long.valueOf(attrValue);
    }
        break;
    case REAL: {
        double attrValue = 0;
        try {
            if (!strValue.equals("")) {
                attrValue = Double.parseDouble(strValue);
            }
        } catch (NumberFormatException nfEx) {
            //        System.out.println("... entry: " + entry.getValue() + " for raw: " + entry.getKey());
            nfEx.printStackTrace();
            throw nfEx;
        }
        retValue = Double.valueOf(attrValue);
    }
        break;
    case STRING:
        retValue = strValue;
        break;
    case BOOLEAN: {
        if (strValue.equalsIgnoreCase("TRUE") || strValue.equals("1")) {
            retValue = Boolean.valueOf(true);
        } else if (strValue.equalsIgnoreCase("FALSE") || strValue.equals("0")) {
            retValue = Boolean.valueOf(false);
        } else {
            LOG.error("Expected Boolean value but got: {}", strValue);
            throw new IllegalStateException("Possible invalid configuration... check mapper vs. schema"
                    + "... or check records for invalid values");
        }
    }
        break;

    case CHARACTER: {
        if (strValue.length() == 1) {
            retValue = Character.valueOf(strValue.charAt(0));
        } else { /* not a char value... report that */
            LOG.error("Expected Character value but got: {}", strValue);
            throw new IllegalStateException("Possible invalid configuration... check mapper vs. schema"
                    + "... or check records for invalid values");
        }
    }
        break;
    case DATE: {
        try {
            LocalDate ldate = LocalDate.parse(strValue, dateFormatter);
            //            System.out.println("... ... year: " + ldate.getYear() + " - month:" + ldate.getMonthValue());
            retValue = new com.objy.db.Date(ldate.getYear(), ldate.getMonthValue(), ldate.getDayOfMonth());
        } catch (DateTimeParseException ex) {
            LOG.error(ex.toString());
            throw new IllegalStateException("Possible invalid configuration... check mapper vs. schema"
                    + "... or check records for invalid values");
        }
    }
        break;
    case DATE_TIME: {
        try {
            //            System.out.println(".... formatter: " + mapper.getDateTimeFormat());
            LocalDateTime ldt = LocalDateTime.parse(strValue, dateTimeFormatter);
            //            System.out.println("... ... year: " + ldt.getYear() + 
            //                    " - month:" + ldt.getMonthValue() + " - day: " +
            //                    ldt.getDayOfMonth() + " - hour: " + ldt.getHour() +
            //                    " - min: " + ldt.getMinute() + " - sec: " + 
            //                    ldt.getSecond() + " - nsec: " + ldt.getNano() );
            //retValue = new com.objy.db.DateTime(date.getTime(), TimeKind.LOCAL);
            retValue = new com.objy.db.DateTime(ldt.getYear(), ldt.getMonthValue(), ldt.getDayOfMonth(),
                    ldt.getHour(), ldt.getMinute(), ldt.getSecond(), ldt.getNano());
        } catch (DateTimeParseException ex) {
            LOG.error(ex.toString());
            throw new IllegalStateException("Possible invalid configuration... check mapper vs. schema"
                    + "... or check records for invalid values");
        }
    }
        break;
    case TIME: {
        try {
            //            System.out.println(".... formatter: " + mapper.getTimeFormat());
            LocalDateTime ltime = LocalDateTime.parse(strValue, dateFormatter);
            //            System.out.println("... ... hour: " + ltime.getHour() +
            //                    " - min: " + ltime.getMinute() + " - sec: " + 
            //                    ltime.getSecond() + " - nsec: " + ltime.getNano() );
            //retValue = new com.objy.db.DateTime(date.getTime(), TimeKind.LOCAL);
            retValue = new com.objy.db.Time(ltime.getHour(), ltime.getMinute(), ltime.getSecond(),
                    ltime.getNano());
        } catch (DateTimeParseException ex) {
            LOG.error(ex.toString());
            throw new IllegalStateException("Possible invalid configuration... check mapper vs. schema"
                    + "... or check records for invalid values");
        }
    }
    default: {
        throw new UnsupportedOperationException("LogicalType: " + logicalType + " is not supported!!!");
    }
    }
    return retValue;
}

From source file:nl.utwente.ewi.caes.tactiletriana.simulation.devices.UncontrollableLoad.java

@Override
public void tick(Simulation simulation, boolean connected) {
    super.tick(simulation, connected);
    LocalDateTime t = simulation.getCurrentTime();
    int minuteOfYear = t.getDayOfYear() * 24 * 60 + t.getHour() * 60 + t.getMinute();
    setCurrentConsumption(profile[profileNumber][minuteOfYear]);
}

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();
    }/*from   w  ww. j  a  v  a 2s  .c  o  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:org.apache.tez.dag.history.logging.proto.DagManifesFileScanner.java

private boolean loadMore() throws IOException {
    LocalDateTime now = manifestLogger.getNow();
    LocalDate today = now.toLocalDate();
    String todayDir = manifestLogger.getDirForDate(today);
    loadNewFiles(todayDir);//  w ww  .j a  va 2s  . c  om
    while (newFiles.isEmpty()) {
        if (now.getHour() * 3600 + now.getMinute() * 60 + now.getSecond() < syncTime) {
            // We are in the delay window for today, do not advance date if we are moving from
            // yesterday.
            if (scanDir.equals(manifestLogger.getDirForDate(today.minusDays(1)))) {
                return false;
            }
        }
        String nextDir = manifestLogger.getNextDirectory(scanDir);
        if (nextDir == null) {
            return false;
        }
        scanDir = nextDir;
        offsets = new HashMap<>();
        retryCount = new HashMap<>();
        loadNewFiles(todayDir);
    }
    return true;
}