Example usage for java.util Date toInstant

List of usage examples for java.util Date toInstant

Introduction

In this page you can find the example usage for java.util Date toInstant.

Prototype

public Instant toInstant() 

Source Link

Document

Converts this Date object to an Instant .

Usage

From source file:net.ceos.project.poi.annotated.core.CellHandler.java

/**
 * Read a date time value from the Cell.
 * //from   w  w w. j a  v  a2 s  .  c o  m
 * @param object
 *            the object
 * @param field
 *            the {@link Field} to set
 * @param cell
 *            the {@link Cell} to read
 * @param xlsAnnotation
 *            the {@link XlsElement} element
 * @throws ConverterException
 *             the conversion exception type
 */
protected static void localDateReader(final Object object, final Field field, final Cell cell,
        final XlsElement xlsAnnotation) throws ConverterException {

    if (StringUtils.isNotBlank(readCell(cell))) {
        try {
            if (StringUtils.isBlank(xlsAnnotation.transformMask())) {
                field.set(object,
                        cell.getDateCellValue().toInstant().atZone(ZoneId.systemDefault()).toLocalDate());
            } else {
                String date = cell.getStringCellValue();

                String tM = xlsAnnotation.transformMask();
                String fM = xlsAnnotation.formatMask();
                String decorator = StringUtils.isEmpty(tM)
                        ? (StringUtils.isEmpty(fM) ? CellStyleHandler.MASK_DECORATOR_DATE : fM)
                        : tM;

                SimpleDateFormat dt = new SimpleDateFormat(decorator);

                Date dateConverted = dt.parse(date);
                field.set(object, dateConverted.toInstant().atZone(ZoneId.systemDefault()).toLocalDate());
            }
        } catch (ParseException | IllegalArgumentException | IllegalAccessException e) {
            /*
             * if date decorator do not match with a valid mask launch
             * exception
             */
            throw new ConverterException(ExceptionMessage.CONVERTER_LOCALDATE.getMessage(), e);
        }
    }
}

From source file:com.example.app.support.service.AppUtil.java

/**
 * Convert the given Date from UTC to a ZonedDateTime at the given TimeZone
 *
 * @param date the UTC date/*from w w  w .j a  va  2  s  . c  o m*/
 * @param zone the TimeZone to convert the time to
 *
 * @return a ZonedDateTime that represents the same instant as the UTC date, but at the given TimeZone.
 */
@Nullable
@Contract(value = "null,_->null;_,null->null;!null,!null->!null", pure = true)
public static ZonedDateTime convertFromPersisted(@Nullable Date date, @Nullable TimeZone zone) {
    if (date == null || zone == null)
        return null;
    ZonedDateTime from = ZonedDateTime.ofInstant(date.toInstant(), ZoneOffset.UTC);
    return from.withZoneSameInstant(zone.toZoneId());
}

From source file:com.ewerk.prototype.persistence.converters.DateToLocalDateConverter.java

@Override
public LocalDate convert(Date source) {
    if (source == null) {
        return null;
    }//ww  w.j  a  v a 2  s  . com
    return source.toInstant().atZone(ZoneId.systemDefault()).toLocalDate();
}

From source file:com.esri.geoportal.harvester.api.base.DataReferenceSerializer.java

private String formatIsoDate(Date date) {
    Instant instant = date.toInstant();
    Calendar cal = Calendar.getInstance();
    cal.setTime(date);//  www. j  a  va  2s.c  om
    ZoneOffset zoneOffset = ZoneOffset.ofHours(cal.getTimeZone().getRawOffset() / (1000 * 60 * 60));
    OffsetDateTime ofInstant = OffsetDateTime.ofInstant(instant, zoneOffset);
    return FORMATTER.format(ofInstant);
}

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);//w w  w  . ja 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:systems.composable.dropwizard.cassandra.cli.CommandInfo.java

@Override
void run(Namespace namespace, CassandraMigration cassandraMigration, Session session) throws Exception {
    final MigrationInfo[] migrationInfos = cassandraMigration.info(session).all();
    if (migrationInfos.length == 0)
        throw new IllegalStateException("No migration scripts found");

    final Map<String, Integer> widths = new HashMap<>();
    final List<Map<String, String>> rows = new LinkedList<>();

    INFOS.forEach(col -> widths.compute(col, (k, v) -> k.length()));
    Arrays.stream(migrationInfos).forEach(migrationInfo -> {
        final Map<String, String> row = new HashMap<>();
        INFOS.forEach(col -> {/*from  ww w.  j  av  a 2 s  .com*/
            final String cell;
            switch (col) {
            case INFO_TYPE:
                cell = migrationInfo.getType().toString();
                break;
            case INFO_STATE:
                cell = migrationInfo.getState().getDisplayName();
                break;
            case INFO_VERSION:
                cell = migrationInfo.getVersion().toString();
                break;
            case INFO_DESC:
                cell = migrationInfo.getDescription();
                break;
            case INFO_SCRIPT:
                cell = migrationInfo.getScript();
                break;
            case INFO_CHKSUM:
                cell = String.valueOf(migrationInfo.getChecksum());
                break;
            case INFO_INST_ON:
                final Date d = migrationInfo.getInstalledOn();
                cell = d != null ? d.toInstant().toString() : "";
                break;
            case INFO_EXEC_MS:
                final Integer ms = migrationInfo.getExecutionTime();
                cell = ms != null ? Duration.of(ms, ChronoUnit.MILLIS).toString() : "";
                break;
            default:
                cell = "";
            }
            row.put(col, cell);
            widths.compute(col, (k, v) -> Math.max(cell.length(), v));
        });
        rows.add(row);
    });

    final String separator = "+"
            + INFOS.stream().map(col -> repeat('-', widths.get(col) + 2)).collect(Collectors.joining("+")) + "+"
            + System.lineSeparator();

    final StringBuilder sb = new StringBuilder().append(separator).append('|')
            .append(INFOS.stream().map(col -> " " + center(col, widths.get(col)) + " ")
                    .collect(Collectors.joining("|")))
            .append('|').append(System.lineSeparator()).append(separator);
    rows.forEach(row -> sb.append('|').append(INFOS.stream()
            .map(col -> " " + leftPad(row.get(col), widths.get(col)) + " ").collect(Collectors.joining("|")))
            .append('|').append(System.lineSeparator()));
    sb.append(separator);
    System.out.print(sb.toString());
}

From source file:org.caratarse.auth.model.dao.UserAttributesTest.java

@Test
public void birthdateUserAttribute() {
    User user = retrieveUserWithAttributes();
    Attribute attribute = user.getUserAttributes().get("birthdate");
    assertTrue(attribute instanceof DateAttribute);
    assertThat(attribute.getName(), is("birthdate"));
    final Date value = new Date(((Date) attribute.getValue()).getTime());
    ZonedDateTime v = value.toInstant().atZone(ZoneId.systemDefault());
    assertThat(v.getDayOfMonth(), is(5));
    assertThat(v.getMonthValue(), is(7));
    assertThat(v.getYear(), is(1980));//from w  w  w.  ja va  2  s.c om
}

From source file:org.caratarse.auth.model.dao.UserAttributesTest.java

@Test
public void lastUserAttribute() {
    User user = retrieveUserWithAttributes();
    Attribute attribute = user.getUserAttributes().get("last");
    assertTrue(attribute instanceof DateTimeAttribute);
    assertThat(attribute.getName(), is("last"));
    final Date value = new Date(((Date) attribute.getValue()).getTime());
    ZonedDateTime v = value.toInstant().atZone(ZoneId.of("UTC"));
    assertThat(v.getDayOfMonth(), is(20));
    assertThat(v.getMonthValue(), is(11));
    assertThat(v.getYear(), is(2015));/* ww  w .j  a va  2  s. c o m*/
    assertThat(v.getHour(), is(12));
    assertThat(v.getMinute(), is(11));
    assertThat(v.getSecond(), is(10));
    assertThat(v.getNano(), is(999000000));
}

From source file:com.orange.clara.cloud.servicedbdumper.task.job.JobFactoryTest.java

@Test
public void when_purge_errored_jobs_and_jobs_in_error_exist_it_should_delete_job_which_pass_expiration() {
    Job jobNotExpired = new Job();
    jobNotExpired.setUpdatedAt(new Date());

    Date date = new Date();
    LocalDateTime localDateTime = LocalDateTime.from(date.toInstant().atZone(ZoneId.systemDefault()))
            .minusDays(jobErroredDeleteExpirationDays + 1);
    Instant instant = localDateTime.atZone(ZoneId.systemDefault()).toInstant();
    Job jobExpired = new Job();
    jobExpired.setUpdatedAt(Date.from(instant));

    when(jobRepo.findByJobEventOrderByUpdatedAtDesc(anyObject()))
            .thenReturn(Arrays.asList(jobNotExpired, jobExpired));
    jobFactory.purgeErroredJobs();/*w  w w.j  a  v a 2s .  com*/
    verify(jobRepo, times(1)).delete((Job) notNull());
}

From source file:com.orange.clara.cloud.servicedbdumper.task.job.JobFactoryTest.java

@Test
public void when_purge_finished_jobs_and_jobs_in_error_exist_it_should_delete_job_which_pass_expiration_and_have_null_database_target_and_source_and_service_instance() {
    Job jobNotExpired = new Job();
    jobNotExpired.setUpdatedAt(new Date());
    jobNotExpired.setDatabaseRefSrc(new DatabaseRef());

    Date date = new Date();
    LocalDateTime localDateTime = LocalDateTime.from(date.toInstant().atZone(ZoneId.systemDefault()))
            .minusMinutes(jobFinishedDeleteExpirationMinutes + 1);
    Instant instant = localDateTime.atZone(ZoneId.systemDefault()).toInstant();
    Job jobExpired = new Job();
    jobExpired.setUpdatedAt(Date.from(instant));

    when(jobRepo.findByJobEventOrderByUpdatedAtDesc(anyObject()))
            .thenReturn(Arrays.asList(jobNotExpired, jobExpired));
    jobFactory.purgeFinishedJob();//from   w  w  w  . j  a  v a2  s. c o m
    verify(jobRepo, times(1)).delete((Job) notNull());
}