Example usage for java.time LocalDate from

List of usage examples for java.time LocalDate from

Introduction

In this page you can find the example usage for java.time LocalDate from.

Prototype

public static LocalDate from(TemporalAccessor temporal) 

Source Link

Document

Obtains an instance of LocalDate from a temporal object.

Usage

From source file:Main.java

/**
 * Parses a String to a ChronoLocalDate using a DateTimeFormatter with a short
 * pattern based on the current Locale and the provided Chronology, then
 * converts this to a LocalDate (ISO) value.
 *
 * @param text//www.  j av a2s . c om
 *          - the input date text in the SHORT format expected for the
 *          Chronology and the current Locale.
 *
 * @param chrono
 *          - an optional Chronology. If null, then IsoChronology is used.
 */
public static LocalDate fromString(String text, Chronology chrono) {
    if (text != null && !text.isEmpty()) {
        Locale locale = Locale.getDefault(Locale.Category.FORMAT);
        if (chrono == null) {
            chrono = IsoChronology.INSTANCE;
        }
        String pattern = "M/d/yyyy GGGGG";
        DateTimeFormatter df = new DateTimeFormatterBuilder().parseLenient().appendPattern(pattern)
                .toFormatter().withChronology(chrono).withDecimalStyle(DecimalStyle.of(locale));
        TemporalAccessor temporal = df.parse(text);
        ChronoLocalDate cDate = chrono.date(temporal);
        return LocalDate.from(cDate);
    }
    return null;
}

From source file:be.wegenenverkeer.common.resteasy.json.Iso8601AndOthersLocalDateTimeFormat.java

/**
 * Parse string to date.//from w  w  w  . j  a 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:fr.lepellerin.ecole.service.internal.CantineServiceImpl.java

@Override
@Transactional(readOnly = true)//from w w w .  j av a 2 s  .c  o  m
public PlanningDto getDateOuvert(final YearMonth anneeMois, final Famille famille) throws TechnicalException {
    final Date startDate = Date.from(Instant.from(anneeMois.atDay(1).atStartOfDay(ZoneId.systemDefault())));
    final Date endDate = Date.from(Instant.from(anneeMois.atEndOfMonth().atStartOfDay(ZoneId.systemDefault())));

    final Activite activite = getCantineActivite();

    final LocalDateTime heureH = LocalDateTime.now();
    final List<Inscription> icts = this.ictRepository.findByActiviteAndFamille(activite, famille);

    final PlanningDto planning = new PlanningDto();

    icts.forEach(ict -> {
        planning.getHeaders().add(ict.getIndividu().getPrenom());
        final List<Consommation> consos = this.consommationRepository
                .findByFamilleInscriptionActiviteUniteEtatsPeriode(famille, activite, ict.getGroupe(),
                        Arrays.asList("reservation"), startDate, endDate);
        final List<Ouverture> ouvertures = this.ouvertureRepository.findByActiviteAndGroupeAndPeriode(activite,
                ict.getGroupe(), startDate, endDate);
        ouvertures.forEach(o -> {
            final LocalDate date = LocalDate.from(((java.sql.Date) o.getDate()).toLocalDate());
            final LocalDateTime heureResa = this.getLimiteResaCantine(date);
            final LigneDto ligne = planning.getOrCreateLigne(date);
            final CaseDto c = new CaseDto();
            c.setDate(date);
            c.setIndividu(ict.getIndividu());
            c.setActivite(o.getActivite());
            c.setUnite(o.getUnite());
            c.setReservable(heureResa.isAfter(heureH));
            final Optional<Consommation> cOpt = consos.stream().filter(conso -> {
                final LocalDate dateConso = LocalDate.from(((java.sql.Date) conso.getDate()).toLocalDate());
                return dateConso.equals(date);
            }).findAny();
            c.setReserve(cOpt.isPresent());
            ligne.getCases().add(c);
        });
    });

    return planning;
}

From source file:com.bdb.weather.display.summary.TemperatureDeviationPlotPanel.java

public TemperatureDeviationPlotPanel(SummaryInterval interval, ViewLauncher theLauncher,
        SummarySupporter theSupporter) {
    this.setPrefSize(500, 300);
    this.interval = interval;
    chart = ChartFactory.createXYBarChart("Deviation from Average Temperature", "Date", true,
            "Deviation (" + Temperature.getDefaultUnit() + ")", null, PlotOrientation.VERTICAL, true, true,
            false);/*from  w ww .  j av a 2s.  c om*/

    chartViewer = new ChartViewer(chart);
    chartViewer.setPrefSize(500, 300);
    chartViewer.addChartMouseListener(new ChartMouseListenerFX() {
        @Override
        public void chartMouseClicked(ChartMouseEventFX event) {
            ChartEntity entity = event.getEntity();
            //
            // Was a point on the plot selected?
            //
            if (entity instanceof XYItemEntity) {
                XYItemEntity itemEntity = (XYItemEntity) entity;
                XYDataset dataset = itemEntity.getDataset();
                Number x = dataset.getXValue(itemEntity.getSeriesIndex(), itemEntity.getItem());
                LocalDate date = LocalDate.from(Instant.ofEpochMilli(x.longValue()));
                boolean doubleClick = event.getTrigger().getClickCount() == 2;
                if (doubleClick) {
                    supporter.launchView(launcher, date);
                }
            }
        }

        @Override
        public void chartMouseMoved(ChartMouseEventFX event) {
            // Do nothing
        }
    });
    deviationPlot = (XYPlot) chart.getPlot();
    this.launcher = theLauncher;
    this.supporter = theSupporter;

    DateFormat dateFormat = interval.getLegacyFormat();
    StandardXYItemLabelGenerator labelGen = new StandardXYItemLabelGenerator(
            StandardCategoryItemLabelGenerator.DEFAULT_LABEL_FORMAT_STRING, dateFormat,
            Temperature.getDefaultFormatter());

    StandardXYToolTipGenerator ttGen = new StandardXYToolTipGenerator(
            StandardCategoryToolTipGenerator.DEFAULT_TOOL_TIP_FORMAT_STRING, dateFormat,
            Temperature.getDefaultFormatter());

    valueAxis = deviationPlot.getRangeAxis();
    valueAxis.setUpperMargin(.20);
    valueAxis.setLowerMargin(.20);

    deviationPlot.getDomainAxis().setVerticalTickLabels(true);
    DateAxis dateAxis = (DateAxis) deviationPlot.getDomainAxis();
    dateAxis.setDateFormatOverride(dateFormat);
    //dateAxis.setTickUnit(interval.getDateTickUnit());

    //DefaultTableColumnModel colModel = new DefaultTableColumnModel();

    dataTable = new TableView();
    //dataTable.setModel(tableModel);
    //dataTable.setColumnModel(colModel);

    //dataTable.setAutoCreateColumnsFromModel(false);

    for (int i = 0; i < TABLE_HEADINGS.length; i++) {
        TableColumn col = new TableColumn();
        col.setText(TABLE_HEADINGS[i]);
        //col.setModelIndex(i);
        //colModel.addColumn(col);
    }

    //tableModel.setColumnCount(TABLE_HEADINGS.length);

    this.setTabContents(chartViewer, dataTable);

    lowRenderer.setBasePaint(Color.BLUE);
    lowRenderer.setBaseItemLabelGenerator(labelGen);
    lowRenderer.setBaseToolTipGenerator(ttGen);
    lowRenderer.setBarAlignmentFactor(.6);
    lowRenderer.setShadowVisible(false);

    meanRenderer.setSeriesPaint(0, Color.CYAN);
    meanRenderer.setBaseItemLabelGenerator(labelGen);
    meanRenderer.setBaseToolTipGenerator(ttGen);
    meanRenderer.setBarAlignmentFactor(.3);
    meanRenderer.setShadowVisible(false);

    highRenderer.setSeriesPaint(0, Color.GRAY);
    highRenderer.setBaseItemLabelGenerator(labelGen);
    highRenderer.setBaseToolTipGenerator(ttGen);
    highRenderer.setShadowVisible(false);
}

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

public GamaDate(final IScope scope, final Temporal d) {
    final ZoneId zone;
    if (d instanceof ChronoZonedDateTime) {
        zone = ZonedDateTime.from(d).getZone();
    } else if (d.isSupported(ChronoField.OFFSET_SECONDS)) {
        zone = ZoneId.ofOffset("", ZoneOffset.ofTotalSeconds(d.get(ChronoField.OFFSET_SECONDS)));
    } else {/*from  w  w w.  j  a va  2 s  . c  om*/
        zone = GamaDateType.DEFAULT_ZONE;
    }
    if (!d.isSupported(MINUTE_OF_HOUR)) {
        internal = ZonedDateTime.of(LocalDate.from(d), LocalTime.of(0, 0), zone);
    } else if (!d.isSupported(DAY_OF_MONTH)) {
        internal = ZonedDateTime.of(LocalDate.from(
                scope == null ? Dates.DATES_STARTING_DATE.getValue() : scope.getSimulation().getStartingDate()),
                LocalTime.from(d), zone);
    } else {
        internal = d;
    }
}

From source file:com.bdb.weather.display.summary.RainSummary.java

@Override
public void chartMouseClicked(ChartMouseEventFX event) {
    ChartEntity entity = event.getEntity();
    ////ww w. j  a  v a 2 s.c o  m
    // Was a point on the plot selected?
    //
    if (entity instanceof CategoryItemEntity) {
        try {
            CategoryItemEntity itemEntity = (CategoryItemEntity) entity;
            LocalDate date = LocalDate.from(interval.getFormat().parse((String) itemEntity.getColumnKey()));

            //if (event.getTrigger().getClickCount() == 2)
            //    supporter.launchView(viewLauncher, date);
        } catch (DateTimeParseException e) {
            // This will never happen because the same date formatter is used to create the category labels and parse the column key
        }
    }
}

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

private static Temporal parse(final IScope scope, final String original, final DateTimeFormatter df) {
    if (original == null || original.isEmpty() || original.equals("now")) {
        return LocalDateTime.now(GamaDateType.DEFAULT_ZONE);
    }//w w w  .jav a  2  s . co m
    Temporal result = null;

    if (df != null) {
        try {
            final TemporalAccessor ta = df.parse(original);
            if (ta instanceof Temporal) {
                return (Temporal) ta;
            }
            if (!ta.isSupported(ChronoField.YEAR) && !ta.isSupported(ChronoField.MONTH_OF_YEAR)
                    && !ta.isSupported(ChronoField.DAY_OF_MONTH)) {
                if (ta.isSupported(ChronoField.HOUR_OF_DAY)) {
                    return LocalTime.from(ta);
                }
            }
            if (!ta.isSupported(ChronoField.HOUR_OF_DAY) && !ta.isSupported(ChronoField.MINUTE_OF_HOUR)
                    && !ta.isSupported(ChronoField.SECOND_OF_MINUTE)) {
                return LocalDate.from(ta);
            }
            return LocalDateTime.from(ta);
        } catch (final DateTimeParseException e) {
            e.printStackTrace();
        }
        GAMA.reportAndThrowIfNeeded(scope,
                GamaRuntimeException.warning(
                        "The date " + original + " can not correctly be parsed by the pattern provided", scope),
                false);
        return parse(scope, original, null);
    }

    String dateStr;
    try {
        // We first make sure all date fields have the correct length and
        // the string is correctly formatted
        String string = original;
        if (!original.contains("T") && original.contains(" ")) {
            string = StringUtils.replaceOnce(original, " ", "T");
        }
        final String[] base = string.split("T");
        final String[] date = base[0].split("-");
        String other;
        if (base.length == 1) {
            other = "00:00:00";
        } else {
            other = base[1];
        }
        String year, month, day;
        if (date.length == 1) {
            // ISO basic date format
            year = date[0].substring(0, 4);
            month = date[0].substring(4, 6);
            day = date[0].substring(6, 8);
        } else {
            year = date[0];
            month = date[1];
            day = date[2];
        }
        if (year.length() == 2) {
            year = "20" + year;
        }
        if (month.length() == 1) {
            month = '0' + month;
        }
        if (day.length() == 1) {
            day = '0' + day;
        }
        dateStr = year + "-" + month + "-" + day + "T" + other;
    } catch (final Exception e1) {
        throw GamaRuntimeException.error("The date " + original
                + " is not correctly formatted. Please refer to the ISO date/time format", scope);
    }

    try {
        result = LocalDateTime.parse(dateStr);
    } catch (final DateTimeParseException e) {
        try {
            result = OffsetDateTime.parse(dateStr);
        } catch (final DateTimeParseException e2) {
            try {
                result = ZonedDateTime.parse(dateStr);
            } catch (final DateTimeParseException e3) {
                throw GamaRuntimeException.error(
                        "The date " + original
                                + " is not correctly formatted. Please refer to the ISO date/time format",
                        scope);
            }
        }
    }

    return result;
}

From source file:com.bdb.weather.display.summary.WindSummary.java

@Override
public void chartMouseClicked(ChartMouseEventFX event) {
    ChartEntity entity = event.getEntity();
    ///*  w  w w  .jav a 2  s .c  o m*/
    // Was a point on the plot selected?
    //
    if (entity instanceof XYItemEntity) {
        XYItemEntity itemEntity = (XYItemEntity) entity;
        XYDataset dataset = itemEntity.getDataset();
        Number x = dataset.getXValue(itemEntity.getSeriesIndex(), itemEntity.getItem());
        LocalDate date = LocalDate.from(Instant.ofEpochMilli(x.longValue()));

        if (event.getTrigger().getClickCount() == 2)
            supporter.launchView(launcher, date);
    }
}

From source file:fr.lepellerin.ecole.service.internal.CantineServiceImpl.java

@Override
@Transactional(readOnly = false)//w  ww. ja v a2  s . c  om
public void reserver(final LocalDate startDate, final Famille famille, final List<DayOfWeek> jours)
        throws TechnicalException {

    final Activite activite = getCantineActivite();
    final List<Inscription> icts = this.ictRepository.findByActiviteAndFamille(activite, famille);
    icts.forEach(ict -> {
        final List<Ouverture> ouvertures = this.ouvertureRepository.findByActiviteAndGroupeAndDateDebut(
                activite, ict.getGroupe(),
                Date.from(Instant.from(startDate.atStartOfDay(ZoneId.systemDefault()))));
        ouvertures.forEach(o -> {
            final LocalDate date = LocalDate.from(((java.sql.Date) o.getDate()).toLocalDate());
            try {
                this.reserver(date, ict.getIndividu().getId(), famille, jours.contains(date.getDayOfWeek()));
            } catch (TechnicalException e) {
                LOGGER.error("Une erreur technique s'est produite : " + e.getMessage(), e);
            } catch (FunctionalException e) {
                LOGGER.warn("Une erreur fonctionnelle s'est produite : " + e.getMessage(), e);
            }
        });
    });
}

From source file:com.bdb.weather.display.summary.HighLowPanel.java

@Override
public void chartMouseClicked(ChartMouseEventFX event) {
    ChartEntity entity = event.getEntity();
    ////from  w w w .j  a  v a 2 s . c om
    // Was a point on the plot selected?
    //
    if (entity instanceof XYItemEntity) {
        XYItemEntity itemEntity = (XYItemEntity) entity;
        XYDataset dataset = itemEntity.getDataset();
        Number x = dataset.getXValue(itemEntity.getSeriesIndex(), itemEntity.getItem());
        LocalDate date = LocalDate.from(Instant.ofEpochMilli(x.longValue()));
        boolean doubleClick = event.getTrigger().getClickCount() == 2;
        if (doubleClick) {
            supporter.launchView(launcher, date);
        }
    }
}