コード例 #1
0
public class DateComparisonUsingLocalDate {

  LocalDate now = LocalDate.now();
  String beginningOfMonth =
      now.withDayOfMonth(1).format(DateTimeFormatter.ofPattern("MM/dd/yyyy", Locale.US));
  String today = now.format(DateTimeFormatter.ofPattern("MM/dd/yyyy", Locale.US));
  String yesterday = now.minusDays(1).format(DateTimeFormatter.ofPattern("MM/dd/yyyy", Locale.US));
  SimpleDateFormat formatter = new SimpleDateFormat("MM/dd/yyyy");

  void checkIfSameDay() throws Exception {
    String startDateStr = "03/03/2011";
    String endDateStr = "03/03/2011";
    Date endDate = formatter.parse(endDateStr);

    boolean isSameDay;
    isSameDay =
        DateUtils.isSameDay(formatter.parse(beginningOfMonth), formatter.parse(startDateStr));
    System.out.println("==1==" + isSameDay);
    isSameDay = DateUtils.isSameDay(formatter.parse(yesterday), endDate);
    System.out.println("==2==" + isSameDay);

    isSameDay = DateUtils.isSameDay(formatter.parse(yesterday), formatter.parse(startDateStr));
    System.out.println("==3==" + isSameDay);
    isSameDay = DateUtils.isSameDay(formatter.parse(yesterday), endDate);
    System.out.println("==4==" + isSameDay);
  }
}
コード例 #2
0
ファイル: TesteData.java プロジェクト: ccaroca/Sistemas_Alura
  public static void main(String[] args) {
    LocalDate hoje = LocalDate.now();
    System.out.println(hoje);

    LocalDate olimpiadasRio = LocalDate.of(2016, Month.JUNE, 5);
    System.out.println(olimpiadasRio);

    int dias = olimpiadasRio.getDayOfYear() - hoje.getDayOfYear();
    System.out.println(dias + " dias para as Olímpiadas no Rio!");

    Period periodo = Period.between(hoje, olimpiadasRio);
    System.out.println(periodo.getMonths() + " meses e " + periodo.getDays() + " dias.");

    DateTimeFormatter formatador = DateTimeFormatter.ofPattern("dd/MM/yyyy");
    String valorFormatado = olimpiadasRio.format(formatador);
    System.out.println(valorFormatado);

    System.out.println(" --- Medida de tempo ---");

    DateTimeFormatter formatadorComHoras = DateTimeFormatter.ofPattern("dd/MM/yyyy hh:mm:ss");
    LocalDateTime agora = LocalDateTime.now();
    System.out.println(agora);
    System.out.println(agora.format(formatadorComHoras));

    LocalTime intervalo = LocalTime.of(12, 30);
    System.out.println(intervalo);
  }
コード例 #3
0
ファイル: Formatting.java プロジェクト: bboyjing/sample
  public static void main(String[] args) {
    ZonedDateTime apollo11launch =
        ZonedDateTime.of(1969, 7, 16, 9, 32, 0, 0, ZoneId.of("America/New_York"));

    String formatted = DateTimeFormatter.ISO_DATE_TIME.format(apollo11launch);
    // 1969-07-16T09:32:00-05:00[America/New_York]
    System.out.println(formatted);

    DateTimeFormatter formatter = DateTimeFormatter.ofLocalizedDateTime(FormatStyle.LONG);
    formatted = formatter.format(apollo11launch);
    // July 16, 1969 9:32:00 AM EDT
    System.out.println(formatted);
    formatted = formatter.withLocale(Locale.FRENCH).format(apollo11launch);
    // 16 juillet 1969 09:32:00 EDT
    System.out.println(formatted);

    formatter = DateTimeFormatter.ofPattern("E yyyy-MM-dd HH:mm");
    formatted = formatter.format(apollo11launch);
    System.out.println(formatted);

    LocalDate churchsBirthday = LocalDate.parse("1903-06-14");
    System.out.println("churchsBirthday: " + churchsBirthday);
    apollo11launch =
        ZonedDateTime.parse(
            "1969-07-16 03:32:00-0400", DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ssxx"));
    System.out.println("apollo11launch: " + apollo11launch);
  }
コード例 #4
0
  /**
   * RFC 2616 allows three different date-formats:
   *
   * <ul>
   *   <li>RFC 1123
   *   <li>RFC 1036
   *   <li>ASCI-Time
   * </ul>
   *
   * @param headerValue value transmitted from client
   * @return the parsed DateTime
   * @see <a href= "http://www.w3.org/Protocols/rfc2616/rfc2616-sec3.html#sec3.3">RFC 2616</a>
   */
  private LocalDateTime convertIfModifiedSinceToDate(String headerValue) {

    LocalDateTime time = null;
    try {
      time = LocalDateTime.parse(headerValue, DateTimeFormatter.RFC_1123_DATE_TIME);
    } catch (DateTimeParseException e) {
      logger.trace("could not parse date with RFC-1123. Will try RFC-1036 format...");
    }

    if (time == null) {
      try {
        final String PATTERN_RFC1036 = "EEE, dd-MMM-yy HH:mm:ss zzz";
        time = LocalDateTime.parse(headerValue, DateTimeFormatter.ofPattern(PATTERN_RFC1036));
      } catch (DateTimeParseException e) {
        logger.trace("could not parse date with RFC-1036. Will try ASCITIME format...");
      }
    }

    if (time == null) {
      try {
        final String PATTERN_ASCITIME = "EEE MMM d HH:mm:ss yyyy";
        time = LocalDateTime.parse(headerValue, DateTimeFormatter.ofPattern(PATTERN_ASCITIME));
      } catch (DateTimeParseException e) {
        logger.trace("could not parse date with ASCITIME.");
      }
    }

    if (time == null) {
      logger.error("Could not parse given if-modified-since header with value '{}'", headerValue);
    }
    return time;
  }
コード例 #5
0
  public void setCheckin(Checkin checkin) {
    this.checkin = checkin;
    if (checkin == null) {
      this.jLabelCode.setText("<html>Kodi: <b>?");
      this.jLabelDate.setText("<html>Data: <b>?");
      this.jLabelTime.setText("<html>Ora: <b>?");
      this.jLabel1.setText("<html>Furnitori<b>?");
      this.jLabelTotValue.setText("<html>Tot.: <>?");
      this.items = new ArrayList();
    } else {
      this.jLabelCode.setText("<html>Kodi: <b>" + checkin.getCode());
      this.jLabelDate.setText(
          "<html>Data: <b>"
              + checkin.getEmissionTime().format(DateTimeFormatter.ofPattern("dd.MM.yyyy")));
      this.jLabelTime.setText(
          "<html>Ora: <b>"
              + checkin.getEmissionTime().format(DateTimeFormatter.ofPattern("HH.mm.ss")));
      this.jLabel1.setText("<html>Furnitori: <b>" + checkin.getSupplier());
      this.jLabelTotValue.setText("<html>Tot.: " + checkin.getValue());
      this.items = checkin.getItems();
    }

    DecimalFormat df = new DecimalFormat();
    df.applyPattern("#,##0.0#");
    String[] header = {"Kodi", "Emertimi", "Marka", "Tipi", "Sasia", "Cmimi", "Vlera"};
    Object[][] data = new Object[this.items.size()][header.length];
    for (int r = 0; r < this.items.size(); r++) {
      data[r][0] = this.items.get(r).getCode();
      data[r][1] = this.items.get(r).getName();
      data[r][2] = this.items.get(r).getBrand();
      data[r][3] = this.items.get(r).getType();
      data[r][4] = this.items.get(r).getQuantity();
      data[r][5] = this.items.get(r).getValue();
      data[r][6] = this.items.get(r).getValue() * this.items.get(r).getQuantity();
    }
    DefaultTableModel dtm =
        new DefaultTableModel(data, header) {
          @Override
          public boolean isCellEditable(int r, int c) {
            return false;
          }

          @Override
          public Class getColumnClass(int columnIndex) {
            Class[] types =
                new Class[] {
                  java.lang.String.class,
                  java.lang.String.class,
                  java.lang.String.class,
                  java.lang.String.class,
                  java.lang.Integer.class,
                  java.lang.Float.class,
                  java.lang.Float.class
                };
            return types[columnIndex];
          }
        };
    this.jTableItems.setModel(dtm);
  }
コード例 #6
0
ファイル: Exam.java プロジェクト: pcarrara21/ExamTable
 public Exam(String name, String day, String hour, String color) {
   this.name = name;
   this.day = day;
   time =
       LocalTime.parse(hour, DateTimeFormatter.ofPattern("HH.mm"))
           .atDate(LocalDate.parse(day, DateTimeFormatter.ofPattern("dd/MM/yy")));
   this.color = color; // don't blame me they're all static methods ^^^		
   this.hour = hour;
 }
コード例 #7
0
 @Override
 public String toString() {
   return "["
       + "checkoutdate:"
       + checkoutDate.format(DateTimeFormatter.ofPattern(Constant.DATE_PATTERN))
       + ", dueDate: "
       + dueDate.format(DateTimeFormatter.ofPattern(Constant.DATE_PATTERN))
       + ", publication: "
       + copy
       + "]";
 }
コード例 #8
0
ファイル: TimeTest.java プロジェクト: zero-jianjia/javatest
  static void f3() {
    DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyMMdd-HH:mm:ss");
    LocalDateTime dateTime = LocalDateTime.now();
    String string = formatter.format(dateTime);
    System.out.println(string);

    DateTimeFormatter formatter1 = DateTimeFormatter.ofPattern("yyyyMMdd-HH:mm:ss");
    LocalDateTime dateTime1 = LocalDateTime.parse("20160124-15:03:59", formatter1);
    System.out.println(dateTime1);

    // LocalDateTime dt1 = LocalDateTime.of(2016, Month.JANUARY, 10, 20, 30);
    // LocalDateTime dt2 = LocalDateTime.of(date, time);
    // LocalDateTime dt3 = date.atTime(20, 30);
    // LocalDateTime dt4 = date.atTime(time);
  }
  @Test
  public void testCreateHtml() throws Exception {
    List<Transaction> result =
        new CsvImporter()
            .importCsv(new FileInputStream("src/test/resources/transactions_example6.csv"), null);

    LocalDate beginPeriod =
        LocalDate.parse("04-02-2016", DateTimeFormatter.ofPattern("dd-MM-yyyy"));
    LocalDate endPeriod = LocalDate.parse("05-03-2016", DateTimeFormatter.ofPattern("dd-MM-yyyy"));
    /*ByteArrayInputStream bStream = new HtmlGenerator().createHtml(result, "134567890", beginPeriod, endPeriod);
    try (OutputStream os = new FileOutputStream("src/test/resources/testHtmlGenerator.html")) {
        IOUtils.copy(bStream, os);
    }*/

  }
コード例 #10
0
ファイル: InfoOperation.java プロジェクト: topriddy/javabot
 @Override
 public boolean handleMessage(final Message event) {
   final String message = event.getValue().toLowerCase();
   final Channel channel = event.getChannel();
   if (message.startsWith("info ")) {
     final String key = message.substring("info ".length());
     final Factoid factoid = dao.getFactoid(key);
     if (factoid != null) {
       DateTimeFormatter formatter = DateTimeFormatter.ofPattern(INFO_DATE_FORMAT);
       LocalDateTime updated = factoid.getUpdated();
       String formatted = formatter.format(updated);
       getBot()
           .postMessageToChannel(
               event,
               Sofia.factoidInfo(
                   key,
                   factoid.getLocked() ? "*" : "",
                   factoid.getUserName(),
                   formatted,
                   factoid.getValue()));
     } else {
       getBot().postMessageToChannel(event, Sofia.factoidUnknown(key));
     }
     return true;
   }
   return false;
 }
コード例 #11
0
 private void handleBirthDateChange() {
   String bdateStr = view.bDateFld.getText();
   if (bdateStr == null || bdateStr.trim().equals("")) {
     model.setBirthDate(null);
     view.syncBirthDate();
   } else {
     try {
       DateTimeFormatter formatter = DateTimeFormatter.ofPattern(view.dateFormat);
       LocalDate bdate = LocalDate.parse(bdateStr, formatter);
       List<String> errorList = new ArrayList<>();
       if (model.isValidBirthDate(bdate, errorList)) {
         model.setBirthDate(bdate);
         view.syncAgeCategory();
       } else {
         this.showError(errorList);
         view.syncBirthDate();
       }
     } catch (DateTimeParseException e) {
       // Birth date is not in the specified date format
       List<String> errorList = new ArrayList<>();
       errorList.add("Birth date must be in the " + view.dateFormat.toLowerCase() + " format.");
       this.showError(errorList);
       // Refresh the view
       view.syncBirthDate();
     }
   }
 }
コード例 #12
0
@Controller
public class ActivityService implements ApplicationListener<SessionDisconnectEvent> {

  private static final Logger log = LoggerFactory.getLogger(ActivityService.class);

  private DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");

  @Inject SimpMessageSendingOperations messagingTemplate;

  @SubscribeMapping("/topic/activity")
  @SendTo("/topic/tracker")
  public ActivityDTO sendActivity(
      @Payload ActivityDTO activityDTO,
      StompHeaderAccessor stompHeaderAccessor,
      Principal principal) {
    activityDTO.setUserLogin(SecurityUtils.getCurrentUserLogin());
    activityDTO.setUserLogin(principal.getName());
    activityDTO.setSessionId(stompHeaderAccessor.getSessionId());
    activityDTO.setIpAddress(stompHeaderAccessor.getSessionAttributes().get(IP_ADDRESS).toString());
    Instant instant = Instant.ofEpochMilli(Calendar.getInstance().getTimeInMillis());
    activityDTO.setTime(
        dateTimeFormatter.format(ZonedDateTime.ofInstant(instant, ZoneOffset.systemDefault())));
    log.debug("Sending user tracking data {}", activityDTO);
    return activityDTO;
  }

  @Override
  public void onApplicationEvent(SessionDisconnectEvent event) {
    ActivityDTO activityDTO = new ActivityDTO();
    activityDTO.setSessionId(event.getSessionId());
    activityDTO.setPage("logout");
    messagingTemplate.convertAndSend("/topic/tracker", activityDTO);
  }
}
コード例 #13
0
ファイル: DateTimeTest.java プロジェクト: zbdbao/java_se
/** Created by zhangb on 22/9/2015. */
public class DateTimeTest {

  DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");

  public static void main(String[] args) {
    DateTimeTest test = new DateTimeTest();

    test.localDateTimeTest();

    test.localDateTest();
  }

  public void localDateTimeTest() {
    LocalDateTime currentTime = LocalDateTime.now();

    System.out.println(currentTime);

    System.out.println(currentTime.format(formatter));
  }

  public void localDateTest() {
    LocalDate localDate = LocalDate.now();
    System.out.println(localDate);
  }
}
コード例 #14
0
  private void setNextRepetitionDate(LocalDate nextRepetitionDate) {
    String formattedNextRepetitionDate =
        nextRepetitionDate.format(DateTimeFormatter.ofPattern("dd.MM.yyyy"));

    nextRepetitionDateTextField.setText(formattedNextRepetitionDate);
    setNextRepetitionDateForeground(nextRepetitionDate);
  }
コード例 #15
0
ファイル: Post.java プロジェクト: anarcoqr/Mais-PoP
  public Post(String mensagem, String data) throws SystemException {
    this.valida = new Valida();
    if (!valida.conteudoPost(mensagem)) {
      throw new PostException("Conteudo do post nao pode ser nulo ou vazio.");
    }

    if (separaMensagem(mensagem, "#").length() >= MAXIMO_CARACTERES) {
      throw new PostException(
          "Nao eh possivel criar o post. O limite maximo da mensagem sao 200 caracteres.");
    }

    if (mensagem.contains("#")) {
      String hashtagErro = valida.hashtags(mensagem);
      if (hashtagErro != null) {
        throw new PostException(
            "Nao eh possivel criar o post. As hashtags devem comecar com '#'."
                + " Erro na hashtag: '"
                + hashtagErro
                + "'.");
      }
    }
    formatador = DateTimeFormatter.ofPattern("dd/MM/uuuu");
    this.pops = 0;
    this.mensagem = separaMensagem(mensagem, ("#"));
    this.data = LocalDate.parse(data.substring(0, data.indexOf(" ")), formatador);
    this.hora = LocalTime.parse(data.substring(data.indexOf(" ") + 1));
    this.hashtags = separaHashtags(mensagem);
    this.curtidas = 0;
    adicionaMidia(mensagem);
  }
コード例 #16
0
  /**
   * Map a list of Computer to a list of ComputerDTO.
   *
   * @param computers the computers to map
   * @return the computers as dto
   */
  public List<ComputerDto> listFromModel(List<Computer> computers) {
    DateTimeFormatter formatter =
        DateTimeFormatter.ofPattern(
            messageSource.getMessage("app.formatDate", null, LocaleContextHolder.getLocale()));
    List<ComputerDto> computersDto = new ArrayList<ComputerDto>();

    for (Computer computer : computers) {
      String introduced = null;
      String discontinued = null;
      long companyId = 0;
      String companyName = null;
      if (null != computer.getIntroduced()) {
        introduced = computer.getIntroduced().format(formatter);
      }
      if (null != computer.getDiscontinued()) {
        discontinued = computer.getDiscontinued().format(formatter);
      }
      if (null != computer.getCompany()) {
        companyId = computer.getCompany().getId();
        companyName = computer.getCompany().getName();
      }

      computersDto.add(
          new ComputerDto.ComputerDtoBuilder(computer.getName())
              .id(computer.getId())
              .companyId(companyId)
              .companyName(companyName)
              .introduced(introduced)
              .discontinued(discontinued)
              .build());
    }
    return computersDto;
  }
コード例 #17
0
  public Optional<String> toImageBlock(Image image) {

    if (!current.currentPath().isPresent()) asciiDocController.saveDoc();

    Path currentPath = current.currentPath().map(Path::getParent).get();
    IOHelper.createDirectories(currentPath.resolve("images"));

    List<String> buffer = new LinkedList<>();
    DateTimeFormatter dateTimeFormatter =
        DateTimeFormatter.ofPattern(asciiDocController.getClipboardImageFilePattern());
    Path path = Paths.get(dateTimeFormatter.format(LocalDateTime.now()));

    Path targetImage = currentPath.resolve("images").resolve(path.getFileName());

    try {
      BufferedImage fromFXImage = SwingFXUtils.fromFXImage(image, null);
      ImageIO.write(fromFXImage, "png", targetImage.toFile());

    } catch (Exception e) {
      logger.error("Problem occured while saving clipboard image {}", targetImage);
    }

    buffer.add(String.format("image::images/%s[]", path.getFileName()));

    if (buffer.size() > 0) return Optional.of(String.join("\n", buffer));

    return Optional.empty();
  }
コード例 #18
0
  /**
   * Map a ComputerDTo to a Computer.
   *
   * @param dto the ComputerDTO to map
   * @return the dto as a computer
   */
  public Computer toComputer(ComputerDto dto) {

    DateTimeFormatter formatter =
        DateTimeFormatter.ofPattern(
            messageSource.getMessage("app.formatDate", null, Locale.getDefault()));
    LocalDate introduced = null;
    LocalDate discontinued = null;

    if (null != dto.getIntroduced() && !dto.getIntroduced().isEmpty()) {
      introduced = LocalDate.parse(dto.getIntroduced(), formatter);
    }
    if (null != dto.getDiscontinued() && !dto.getDiscontinued().isEmpty()) {
      discontinued = LocalDate.parse(dto.getDiscontinued(), formatter);
    }
    Company company = null;
    if (dto.getCompanyId() != 0) {
      company = new Company(dto.getCompanyId(), dto.getCompanyName());
    }

    return new Computer.ComputerBuilder(dto.getName())
        .id(dto.getId())
        .company(company)
        .introduced(introduced)
        .discontinued(discontinued)
        .build();
  }
コード例 #19
0
public class DateSerializer extends Serializer<LocalDate> {

  private static final String STR = "uuuu-MM-dd";
  private static final DateTimeFormatter DATE = DateTimeFormatter.ofPattern(STR);

  public static final PgType PGTYPE =
      new PgType.Builder().name("date").oid(1082).arrayId(1182).build();

  public static final DateSerializer instance = new DateSerializer();

  private DateSerializer() {
    super(LocalDate.class);
  }

  public LocalDate fromString(final String str) {
    return LocalDate.parse(str, DATE);
  }

  public LocalDate read(final Stream stream, final int size) {
    return isNull(size) ? null : fromString(str(stream, size, ASCII_ENCODING));
  }

  public int length(final LocalDate d) {
    // yyyy-mm-dd -> 10
    return (d == null) ? NULL_LENGTH : 10;
  }

  public void write(final Stream stream, final LocalDate val) {
    stream.putString(val.format(DATE));
  }
}
コード例 #20
0
  private static void executeJob(String jobId) {
    long execID = 0;
    // ジョブの開始時はXML読み込みなど同時実行されるとおかしくなる処理があるので、ジョブID単位で同期化しておく。
    JobOperator jobOperator = BatchRuntime.getJobOperator();
    synchronized (jobId) {
      Properties props = new Properties();
      props.setProperty(
          "date", LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd")));
      execID = jobOperator.start(jobId, props);
      System.out.println("job stated id:" + execID);
    }
    JobExecution jobExec = null;
    // ジョブが終了するまでポーリング
    while (true) {
      jobExec = jobOperator.getJobExecution(execID);

      if (jobExec.getEndTime() != null) {
        break;
      }

      try {
        Thread.sleep(1000L);
      } catch (InterruptedException ex) {
      }
    }
    System.out.println("JOB END:Status is " + jobExec.getExitStatus());
  }
コード例 #21
0
 @Override
 public QuoteResponse getQuote(
     String sender,
     String fromAddress,
     String fromzipcode,
     String fromcity,
     String receiver,
     String toAddress,
     String tozipcode,
     String tocity,
     double height,
     double width,
     double depth,
     double weight,
     String pickupDate) {
   Parcel parcel = new Parcel("parcel_", StatusParcel.UNKNOWN, width, height, depth, weight);
   parcel.idParcel += parcel.dimension.getVolume();
   LocalDateTime date =
       LocalDateTime.parse(pickupDate, DateTimeFormatter.ofPattern("uuuu-MM-dd'_'HH:mm"));
   Quote q =
       new Quote(
           "idquote1234",
           new Company(sender),
           new Address(fromAddress, fromzipcode, fromcity),
           new Company(receiver),
           new Address(toAddress, tozipcode, tocity),
           parcel,
           date);
   q.setIdQuote("idQuote_" + q.getParcel().idParcel);
   daoContractors.addQuote(q);
   return q.calculateQuote();
 }
コード例 #22
0
@ServerEndpoint("/clock")
public class WebSocketClock {
  static ScheduledExecutorService timer = Executors.newSingleThreadScheduledExecutor();

  private static Set<Session> allSessions;

  DateTimeFormatter timeFormatter = DateTimeFormatter.ofPattern("HH:mm:ss");

  @OnOpen
  public void showTime(Session session) {
    allSessions = session.getOpenSessions();

    // start the scheduler on the very first connection
    // to call sendTimeToAll every second
    if (allSessions.size() == 0) {
      timer.scheduleAtFixedRate(() -> sendTimeToAll(session), 0, 5, TimeUnit.SECONDS);
    }
  }

  private void sendTimeToAll(Session session) {
    allSessions = session.getOpenSessions();
    for (Session sess : allSessions) {
      try {
        sess.getBasicRemote().sendText("Local time: " + LocalTime.now().format(timeFormatter));
      } catch (IOException ioe) {
        System.out.println(ioe.getMessage());
      }
    }
  }
}
コード例 #23
0
@Configuration
public class JacksonConfiguration {

  public static final DateTimeFormatter ISO_FIXED_FORMAT =
      DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'").withZone(ZoneId.of("Z"));

  public static final DateTimeFormatter ISO_DATE_OPTIONAL_TIME =
      new DateTimeFormatterBuilder()
          .append(DateTimeFormatter.ISO_LOCAL_DATE)
          .optionalStart()
          .appendLiteral('T')
          .append(DateTimeFormatter.ISO_TIME)
          .toFormatter();

  @Autowired private Jackson2ObjectMapperBuilder builder;

  // To be replaced by a Jackson2ObjectMapperBuilderCustomizer in Spring-boot 1.4
  @PostConstruct
  public void postConstruct() {
    this.builder.serializers(new ZonedDateTimeSerializer(ISO_FIXED_FORMAT));
    // Will not be needed anymore with SB 1.4 (Jackson > 2.7.1)
    this.builder.deserializerByType(
        LocalDate.class, new LocalDateDeserializer(ISO_DATE_OPTIONAL_TIME));
  }

  @Bean
  public ObjectMapper jacksonObjectMapper() {
    return this.builder.createXmlMapper(false).build();
  }
}
    @Property
    public void shouldHold(
        @InRange(min = "12/31/2012T23:59:59.999999999", format = "MM/dd/yyyy'T'HH:mm:ss.n")
            LocalDateTime t) {

      DateTimeFormatter formatter = DateTimeFormatter.ofPattern("MM/dd/yyyy'T'HH:mm:ss.n");
      assertThat(
          t, greaterThanOrEqualTo(LocalDateTime.parse("12/31/2012T23:59:59.999999999", formatter)));
    }
コード例 #25
0
 @Override
 public Receipt bookTransportation(
     String sender,
     String fromAddress,
     String fromzipcode,
     String fromcity,
     String receiver,
     String toAddress,
     String tozipcode,
     String tocity,
     double height,
     double width,
     double depth,
     double weight,
     String pickupDate,
     String payer,
     String card,
     String reduction) {
   Double reduc = Double.parseDouble(reduction);
   Parcel parcel = new Parcel("parcel_", StatusParcel.UNKNOWN, width, height, depth, weight);
   parcel.idParcel += parcel.dimension.getVolume();
   LocalDateTime date =
       LocalDateTime.parse(pickupDate, DateTimeFormatter.ofPattern("uuuu-MM-dd'_'HH:mm"));
   Quote q =
       new Quote(
           "idquote1234",
           new Company(sender),
           new Address(fromAddress, fromzipcode, fromcity),
           new Company(receiver),
           new Address(toAddress, tozipcode, tocity),
           parcel,
           date);
   daoContractors.addQuote(q);
   q.calculateQuote();
   Transportation transportation = new Transportation(q, new Company(payer), true, card);
   double price = transportation.quote.getCost() - (transportation.quote.getCost() * reduc);
   // TODO payment
   transportation.isPayed = true;
   daoTranportation.addTransportation(transportation);
   String paymentDate =
       LocalDateTime.now().format(DateTimeFormatter.ofPattern("uuuu-MM-dd'_'HH:mm"));
   return new Receipt(
       transportation.quote.getIdQuote(), paymentDate, price, transportation.quote.getEtaString());
 }
コード例 #26
0
ファイル: TestZeit.java プロジェクト: korni1985/HelloGitHub
  public static void main(String[] args) {

    LocalDate jetzt = LocalDate.now();
    DateTimeFormatter myformatter = DateTimeFormatter.ofPattern("EEEE, d. MMM yyyy");
    System.out.println("Heute ist " + myformatter.format(jetzt) + ".");
    System.out.println("ein weiteres Bespiel.....");
    java.util.Random r = new java.util.Random();
    int x = r.nextInt(1000);
    System.out.println("eine Zufallszahl: " + x);
  }
コード例 #27
0
ファイル: Treasury.java プロジェクト: ciukstar/eupp
 @PostLoad
 void init() {
   DecimalFormatSymbols symbols = DecimalFormatSymbols.getInstance();
   symbols.setDecimalSeparator(getDecimalSeparator().charAt(0));
   decimalFormatter = new DecimalFormat(getNumberFormatPattern(), symbols);
   decimalFormatter.setGroupingUsed(getGroupingUsed());
   decimalFormatter.setMaximumFractionDigits(getMaximumFractionDigits());
   decimalFormatter.setMinimumFractionDigits(getMinimumFractionDigits());
   dateTimeFormatter = DateTimeFormatter.ofPattern(getDateFormatPattern());
 }
コード例 #28
0
 @Test
 public void testBindLocalTimeWithSpecificFormatter() throws Exception {
   DateTimeFormatterRegistrar registrar = new DateTimeFormatterRegistrar();
   registrar.setTimeFormatter(DateTimeFormatter.ofPattern("HHmmss"));
   setUp(registrar);
   MutablePropertyValues propertyValues = new MutablePropertyValues();
   propertyValues.add("localTime", "130000");
   binder.bind(propertyValues);
   assertEquals(0, binder.getBindingResult().getErrorCount());
   assertEquals("130000", binder.getBindingResult().getFieldValue("localTime"));
 }
コード例 #29
0
 public LongTemporalPatternVerifier(
     TemporalField field,
     TemporalUnit unit,
     String pattern,
     long min,
     long max,
     boolean fixedLength) {
   super(field, unit, min, max);
   _fixedLength = fixedLength;
   _formatter = DateTimeFormatter.ofPattern(pattern).withResolverStyle(ResolverStyle.SMART);
 }
コード例 #30
0
  /**
   * Uses <code>List workoutHistoryLog</code> to build the bar chart series:
   *
   * <ul>
   *   <li>Selects the last 7 days of workout history
   *   <li>retrieves history data and formats dates for <code>xDateAxis</code> and total workout
   *       time for that day for the <code>yWorkoutTimeAxis</code>
   *   <li>adds all data to the series
   * </ul>
   */
  private void makeWeekSeriesFromAccountHistory() {

    Locale eng = Locale.UK;
    LocalDateTime today = LocalDateTime.now();

    String inputPattern = "yyyyMMddHHmm";
    DateTimeFormatter inputFormatter = DateTimeFormatter.ofPattern(inputPattern, eng);

    String outputPattern = "EEEE"; // day with text
    DateTimeFormatter outputFormatter = DateTimeFormatter.ofPattern(outputPattern, eng);

    // Variables for history entries
    String inputDate;
    long timeToComplete;

    // LocalDateTime object for input date
    LocalDateTime dateOfCompletion;
    // String output for axis
    String formattedDateForAxis;

    long lastDate;

    // Search all workout entries in account's workout history
    // parse the input date string into a LocalDateTime for pattern formatting
    // find entries that are within the last week
    // add date against workout time to series
    for (WorkoutEntry entry : workoutHistoryLog) {

      // Get workout date from history entry
      inputDate = entry.getWorkoutDate();
      dateOfCompletion = LocalDateTime.parse(inputDate, inputFormatter);

      formattedDateForAxis = dateOfCompletion.format(outputFormatter);

      // Check if within the last 7 days
      if (dateOfCompletion.until(today, ChronoUnit.WEEKS) == 0) {
        timeToComplete = entry.getWorkoutTime();
        seriesW.getData().add(new XYChart.Data(formattedDateForAxis, timeToComplete));
      }
    }
  }