Example usage for org.joda.time LocalDateTime LocalDateTime

List of usage examples for org.joda.time LocalDateTime LocalDateTime

Introduction

In this page you can find the example usage for org.joda.time LocalDateTime LocalDateTime.

Prototype

public LocalDateTime(Object instant) 

Source Link

Document

Constructs an instance from an Object that represents a datetime.

Usage

From source file:propel.core.utils.StringUtils.java

License:Open Source License

/**
 * Parses a DateTime from a string. Uses common ISO formats as well as some locale-specific formats. See
 * http://joda-time.sourceforge.net/apidocs/org/joda/time/format/DateTimeFormat.html ISO format examples:
 * <ul>/*from w  w  w .j a v  a2s.  c o m*/
 * <li>yyyyMMdd'T'HHmmssZ</li>
 * <li>yyyyMMdd'T'HHmmss.SSSZ</li>
 * <li>yyyy-MM-dd</li>
 * <li>yyyy-MM-dd'T'HH:mm:ss.SSS</li>
 * <li>yyyy-MM-dd'T'HH:mm:ssZZ</li>
 * <li>yyyy-MM-dd'T'HH:mm:ss.SSSZZ</li>
 * <li>yyyy-MM-dd HH:mm:ss</li>
 * <li>yyyy-MM-dd HH:mm:ss.SSSSSSS</li>
 * <li>yyyy-MM-dd'T'HH:mm:ss</li>
 * <li>yyyy-MM-dd'T'HH:mm:ss.SSSSSSS</li>
 * </ul>
 * <p/>
 * Also supports non-ISO formats such as yyyy/MM/dd. Furthermore attempts to parse using locale-specific parsers.
 * 
 * @throws NullPointerException An argument is null.
 * @throws NumberFormatException Parsed value is outside of configured range, or not of correct type.
 */
@Validate
public static LocalDateTime parseDateTime(@NotNull final String value) {
    LocalDateTime result = null;

    // attempt ISO standard parsing
    try {
        result = STANDARD_FORMATTERS.parseDateTime(value).toLocalDateTime();
    } catch (Throwable e) {
        // continues parsing attempts
    }

    if (result == null)
        // first try locale-specific date/time parsing
        for (int dateStyle = DateFormat.FULL; dateStyle <= DateFormat.SHORT; dateStyle++)
            for (int timeStyle = DateFormat.FULL; timeStyle <= DateFormat.SHORT; timeStyle++)
                if (result == null)
                    try {
                        // Parse with a default format
                        Date date = DateFormat.getDateTimeInstance(dateStyle, timeStyle, CURRENT_LOCALE)
                                .parse(value);
                        result = new LocalDateTime(date);

                        break;
                    } catch (ParseException e) {
                        continue;
                    }

    if (result == null)
        // now try locale-specific date parsing
        for (int dateStyle = DateFormat.FULL; dateStyle <= DateFormat.SHORT; dateStyle++)
            try {
                // Parse with a default format
                Date date = DateFormat.getDateInstance(dateStyle, CURRENT_LOCALE).parse(value);
                result = new LocalDateTime(date);
                break;
            } catch (ParseException e) {
                continue;
            }

    if (result == null)
        // lastly try locale-specific time parsing
        for (int timeStyle = DateFormat.FULL; timeStyle <= DateFormat.SHORT; timeStyle++)
            try {
                // Parse with a default format
                Date date = DateFormat.getTimeInstance(timeStyle, CURRENT_LOCALE).parse(value);
                result = new LocalDateTime(date);
                break;
            } catch (ParseException e) {
                continue;
            }

    if (result == null)
        throw new NumberFormatException("The specified date/time is not in an identifiable format: " + value);

    // sanity check
    if (result.compareTo(MIN_DATETIME) < 0)
        throw new NumberFormatException(
                "Value (" + result + ") was less than allowed minimum (" + MIN_DATETIME + ").");
    if (result.compareTo(MAX_DATETIME) > 0)
        throw new NumberFormatException(
                "Value (" + result + ") was more than allowed maximum (" + MAX_DATETIME + ").");

    return result;
}

From source file:qunar.tc.qmq.delay.store.log.ScheduleOffsetResolver.java

License:Apache License

public static long resolveSegment(long offset, int scale) {
    LocalDateTime localDateTime = new LocalDateTime(offset);
    long year = year(localDateTime);
    long month = month(localDateTime);
    long day = day(localDateTime);
    long hour = hour(localDateTime);
    long minute = minute(localDateTime);
    minute = minute - (minute % scale);/*from  w w  w . j a v  a2  s. c o m*/
    return year + month + day + hour + minute;
}

From source file:se.inera.certificate.web.service.CertificateServiceImpl.java

License:Open Source License

@Override
public UtlatandeMetaData setCertificateStatus(String civicRegistrationNumber, String id,
        LocalDateTime timestamp, String recipientId, StatusType type) {
    UtlatandeMetaData result = null;//from  w  w w. j  a v a  2  s.co  m
    SetCertificateStatusRequestType req = new SetCertificateStatusRequestType();
    req.setCertificateId(id);
    req.setNationalIdentityNumber(civicRegistrationNumber);
    req.setStatus(type);
    req.setTarget(recipientId);
    req.setTimestamp(new LocalDateTime(timestamp));

    final SetCertificateStatusResponseType response = setStatusService.setCertificateStatus(null, req);

    if (response.getResult().getResultCode().equals(ResultCodeEnum.OK)) {
        List<UtlatandeMetaData> updatedList = this.getCertificates(civicRegistrationNumber);
        for (UtlatandeMetaData meta : updatedList) {
            if (meta.getId().equals(id)) {
                result = meta;
                break;
            }
        }

    }
    return result;
}

From source file:se.inera.statistics.hsa.adapter.LocalDateAdapter.java

License:Open Source License

/**
 * Converts an xs:datetime to a Joda Time LocalDateTime.
 *//* ww w.  jav a  2s.  com*/
public static LocalDateTime parseDateTime(String dateString) {

    // crop timezone information ('+...')
    return new LocalDateTime(dateString.replaceAll(TIMEZONE_PATTERN, ""));
}

From source file:siddur.solidtrust.azure.AzureConnector.java

private static LocalDateTime toLocalDateTime(Date d) {
    if (d == null) {
        return null;
    }/* w  w w .ja  v  a  2 s.  c  o m*/
    LocalDateTime l = new LocalDateTime(d.getTime());
    return l;
}

From source file:uk.co.onehp.trickle.domain.Race.java

License:Open Source License

public Race() {
    this.eventId = 0;
    this.name = "";
    this.startTime = new LocalDateTime(0);
    this.meetingName = "";
    this.complete = false;
}

From source file:view.ConfigInternalFrame.java

private void BackupBtnActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_BackupBtnActionPerformed
    Runnable t1 = () -> {/*  w w w.j  av  a2  s .  c om*/
        try {
            java.io.File file = new java.io.File(
                    System.getProperty("user.home") + System.getProperty("file.separator") + ".jbiblioteca"
                            + System.getProperty("file.separator") + "jbiblioteca_bkp.db");
            Database.checkDatabase();
            Database.backupDatabase(file);
            Runnable t2 = () -> {
                try {
                    LocalDateTime ldt = new LocalDateTime(System.currentTimeMillis());
                    ConfigController.saveLastBackupDate("'" + ldt.toString() + "'");
                    backupLabel.setText(ldt.toDate().toLocaleString());

                } catch (Exception e1) {
                }
            };
            new Thread(t2).start();
            JOptionPane.showMessageDialog(null, "O arquivo de backup foi salvo com xito.");
        } catch (Exception e1) {
        }
    };
    new Thread(t1).start();
}

From source file:view.EmprestimoAddInternalFrame.java

public EmprestimoAddInternalFrame() {
    initComponents();// ww  w .ja v a 2  s  .  c  o  m
    /* Passando valor default salvo em Opes>Preferencias>Prazo Default */
    prazo_default = ConfigController.getPrazoDefault();
    diaSpinner.setValue(prazo_default);

    model = new DefaultListModel();
    livroList.setModel(model);

    selecionados = new ArrayList<>();
    filtrados = new ArrayList<>();
    pessoas = PessoaController.ArrayPessoa("");
    exemplares = ExemplarController.ArrayExemplar(null, 0, "");
    updatePessoaBox();
    updateLivroBox();

    ldt = new LocalDateTime(System.currentTimeMillis());
    String date = " " + ldt.getDayOfMonth() + "/" + ldt.getMonthOfYear() + "/" + ldt.getYear() + " ";
    dataLabel.setText("" + date);

}

From source file:view.EmprestimoAddInternalFrame.java

private void salvarEmprestimoBtnActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_salvarEmprestimoBtnActionPerformed
    if (model.getSize() > 0 && !selecionados.isEmpty()) {
        if (pessoaBox.getSelectedIndex() > -1) {
            salvarEmprestimoBtn.setEnabled(false);
            String codigo_pessoa = pessoaBox.getSelectedItem().toString();
            Pessoa alugador = new Pessoa(0, 0, null, null, null);
            for (Pessoa p : pessoas) {
                if (codigo_pessoa.equals(p.getCodigo())) {
                    alugador = p;/* w w w  .  j a  va  2s.  c om*/
                    pessoas.remove(p);
                    break;
                }
            }
            int plus_days = Integer.valueOf(diaSpinner.getValue().toString());
            LocalDateTime inicio = new LocalDateTime(System.currentTimeMillis());
            LocalDateTime fim = inicio.plusDays(plus_days);
            if (EmprestimoController.Salvar(alugador.getId_pessoa(), selecionados, inicio, fim)) {
                Runnable t1 = () -> {
                    if (eif != null)
                        eif.updateEmprestimoTable("");
                    if (lif != null)
                        lif.updateExemplarTableModel("");
                    exemplares.removeAll(selecionados);
                    updateLivroBox();
                    updatePessoaBox();
                    selecionados.clear();
                    model = new DefaultListModel();
                    diaSpinner.setValue(prazo_default);
                    livroList.setModel(model);
                };
                new Thread(t1).start();

                salvarEmprestimoBtn.setEnabled(true);
                //pessoaBox.setSelectedIndex(0);
                pessoaLabel.setText("Cdigo, nome, turma:");
                buscaPessoaField.setText("");
                buscaLivroField.setText("");
                //livroBox.setSelectedIndex(0);
                codigoLabel.setText("Selecione o Cdigo:");
                escolhePessoaBtn.setEnabled(true);
                pessoaBox.setEnabled(true);
            } else
                salvarEmprestimoBtn.setEnabled(true);
        } else
            JOptionPane.showMessageDialog(null, "Selecione uma pessoa. ", "Ateno",
                    JOptionPane.WARNING_MESSAGE);
    } else
        JOptionPane.showMessageDialog(null, "Selecione ao menos um exemplar. ", "Ateno",
                JOptionPane.WARNING_MESSAGE);

}

From source file:view.EmprestimoInternalFrame.java

private void DevolveEmprestimoBtnActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_DevolveEmprestimoBtnActionPerformed
    int idx[] = emprestimoTable.getSelectedRows();
    if (idx.length > 0) {
        int id_emprestimo = Integer
                .valueOf(emprestimoTable.getValueAt(emprestimoTable.getSelectedRow(), 0).toString());
        if (id_emprestimo != 0) {
            Emprestimo e = EmprestimoController.Pegar(id_emprestimo);
            LocalDateTime hoje = new LocalDateTime(System.currentTimeMillis());
            LocalDateTime fim = new LocalDateTime(e.getData_fim());
            int dias = Days.daysBetween(hoje, fim).getDays();
            dias = dias * -1;/*from w  ww  . j  a v a  2  s. c om*/
            double total = 0.0;
            int response;
            if (dias > 0) {
                for (int i = 0; i < dias; i++) {
                    total = e.getId_exemplar().stream().map((_item) -> juros_dia).reduce(total,
                            (accumulator, _item) -> accumulator + _item);
                }
            }

            JLabel nome = new JLabel();
            nome.setFont(new Font("Dialog", Font.BOLD, 14));
            JLabel juros = new JLabel();
            juros.setFont(new Font("Dialog", Font.BOLD, 14));
            JLabel total_ex = new JLabel();
            total_ex.setFont(new Font("Dialog", Font.BOLD, 14));
            Object[] message = { "Locatrio:", nome, "Total de Exemplares: ", total_ex, "Total de Juros:",
                    juros, "Prosseguir com devoluo?" };
            nome.setText(emprestimoTable.getValueAt(emprestimoTable.getSelectedRow(), 1).toString());
            juros.setText("" + NumberFormat.getCurrencyInstance().format(total));
            total_ex.setText("" + e.getId_exemplar().size());

            response = JOptionPane.showConfirmDialog(null, message, "Devoluo", JOptionPane.YES_NO_OPTION,
                    JOptionPane.QUESTION_MESSAGE);
            if (response == JOptionPane.YES_OPTION) {
                if (EmprestimoController.Apagar(id_emprestimo)) {
                    updateEmprestimoTable("");
                    if (lif != null)
                        lif.updateExemplarTableModel("");
                }
            }
        }
    } else {
        DevolveEmprestimoBtn.setEnabled(false);
    }
}