Search in sources :

Example 71 with Period

use of java.time.Period in project jdk8u_jdk by JetBrains.

the class TCKPeriod method test_minusMonths_overflowTooSmall.

@Test(expectedExceptions = ArithmeticException.class)
public void test_minusMonths_overflowTooSmall() {
    Period test = Period.ofMonths(Integer.MIN_VALUE);
    test.minusMonths(1);
}
Also used : Period(java.time.Period) Test(org.testng.annotations.Test)

Example 72 with Period

use of java.time.Period in project jdk8u_jdk by JetBrains.

the class TCKPeriod method factory_between_LocalDate.

@Test(dataProvider = "between")
public void factory_between_LocalDate(int y1, int m1, int d1, int y2, int m2, int d2, int ye, int me, int de) {
    LocalDate start = LocalDate.of(y1, m1, d1);
    LocalDate end = LocalDate.of(y2, m2, d2);
    Period test = Period.between(start, end);
    assertPeriod(test, ye, me, de);
//assertEquals(start.plus(test), end);
}
Also used : Period(java.time.Period) LocalDate(java.time.LocalDate) Test(org.testng.annotations.Test)

Example 73 with Period

use of java.time.Period in project jdk8u_jdk by JetBrains.

the class TCKPeriod method test_minusYears_overflowTooSmall.

@Test(expectedExceptions = ArithmeticException.class)
public void test_minusYears_overflowTooSmall() {
    Period test = Period.ofYears(Integer.MIN_VALUE);
    test.minusYears(1);
}
Also used : Period(java.time.Period) Test(org.testng.annotations.Test)

Example 74 with Period

use of java.time.Period in project algorithms by Iurii-Dziuban.

the class Main method main.

public static void main(String[] args) {
    // Optional
    // Optional.of(null); // Null pointer
    Optional<Integer> emptyOptional = Optional.empty();
    Optional<Integer> nullableOptional = Optional.ofNullable(null);
    Optional<Integer> fiveOptional = Optional.ofNullable(5);
    System.out.println("Nullable.equals.Empty = " + emptyOptional.equals(nullableOptional));
    System.out.println("emptyOrElse = " + emptyOptional.orElse(5));
    System.out.println("fiveOptional = " + fiveOptional);
    System.out.println("fiveOptionalGet = " + fiveOptional.get());
    System.out.println("fiveOptionalGet = " + fiveOptional.orElse(6));
    System.out.println("fiveOptionalGet = " + fiveOptional.orElseGet(() -> 7));
    // --------------- Exception handling -----------------
    try {
        String s = null;
        // this will be thrown
        s.length();
    } catch (NullPointerException e) {
    } finally {
        try {
            // int i = Integer.parseInt(args[0]); // ArrayIndexOutOfBoundsException
            // ArrayIndexOutOfBoundsException
            int k = Integer.parseInt("1ee");
        } catch (NumberFormatException e) {
            // 
            System.out.println("NumberFormatException");
        } finally {
            System.out.println("Finally");
        }
    }
    // -------------- Data structures ---------------------------
    List<Integer> intArr = new ArrayList<Integer>();
    intArr.add(1);
    intArr.add(2);
    intArr.add(3);
    intArr.add(4);
    intArr.removeIf(e -> e % 2 == 0);
    System.out.println(intArr);
    // only TreeSet has pollFirst and ceiling
    TreeSet treeSet = new TreeSet();
    treeSet.add("A");
    treeSet.add("D");
    // no poll method
    treeSet.pollFirst();
    System.out.println(treeSet.ceiling("D"));
    Map<Integer, String> map = new TreeMap<>();
    map.put(1, "One");
    map.put(2, "Two");
    map.put(3, "Three");
    // replace if key and value to value. But value is different - no replace
    map.replace(1, "1", null);
    // null is a valid value
    map.replace(3, null);
    // map.putIfAbsent(null, null); // null if not supported by default. Only if comparator supports
    System.out.println(map.keySet());
    System.out.println(map.values());
    System.out.println(Arrays.asList("Fred", "Jim", "Sheila").stream().peek(System.out::println).allMatch(s -> s.startsWith("F")));
    Map map1 = new HashMap();
    map1.put("One", 1);
    map1.put("Two", 2);
    map1.put("Three", 3);
    map1.put("Four", 4);
    System.out.println(new TreeMap(map1).ceilingKey("O"));
    ArrayDeque ad = new ArrayDeque();
    ad.add(6);
    ad.add(2);
    ad.offerLast(3);
    ad.offer(4);
    ad.poll();
    System.out.println(ad);
    // -------------- Functional programming --------------------
    // unary operator composition
    LongUnaryOperator longUnaryOperator2x = x -> 2 * x;
    LongUnaryOperator longUnaryOperator1PlusX = x -> 1 + x;
    System.out.println(longUnaryOperator2x.compose(longUnaryOperator1PlusX).andThen(longUnaryOperator1PlusX).applyAsLong(5));
    // stream
    Stream<String> stream = Stream.of("Cat", "Dog", "Rat");
    System.out.println(stream.flatMap(st -> Stream.of(st.length())).collect(Collectors.toSet()));
    // ranges inclusive, exclusive
    IntStream.range(0, 9).forEach(System.out::print);
    System.out.println();
    IntStream.rangeClosed(0, 9).forEach(System.out::print);
    System.out.println();
    // comparator
    Comparator<Name> stringComparator = Comparator.comparing(Name::getName);
    System.out.println(stringComparator.compare(new Name("Aaa"), new Name("Bccc")));
    Comparator<Integer> integerComparator = Integer::compare;
    System.out.println(integerComparator.compare(3, 2));
    Comparable<String> compString = s -> s.hashCode();
    // zero is printed
    Stream.of(3, 6, 0, 4).sorted().peek(System.out::print).findFirst();
    Stream ints = Stream.of(1, 2, 3);
    // long value!!
    long count = ints.skip(1).limit(1).count();
    System.out.println("Count = " + count);
    String[] s = new String[2];
    // System.out.println(Optional.of(s[1]).orElse("empty")); // Null pointer -> use Optional.ofNullable
    System.out.println("Null Last = " + Comparator.nullsLast(Integer::compare).compare(null, 10));
    // --------------- Localization -----------------
    System.out.println(DateFormat.getDateInstance(DateFormat.LONG, new Locale("fr")).format(new Date()));
    Locale localeBuilder = new Locale.Builder().setLanguage("en").setRegion("US").build();
    // "anglais" in English language
    System.out.println(localeBuilder.getDisplayLanguage(new Locale("fr")));
    // -------------- Date Time API ----------------------
    // use of Local time api
    System.out.println(LocalTime.ofSecondOfDay(36000));
    System.out.println(LocalTime.ofSecondOfDay(36000).atOffset(ZoneOffset.UTC));
    // use offset time
    System.out.println(OffsetTime.now());
    // use of period
    System.out.println(LocalDate.parse("2016-01-26").plus(PERIOD_DAYS));
    System.out.println(LocalDate.parse("2010-01-21").plus(PERIOD_DAYS).plus(PERIOD_DAYS));
    // compare two dates. not equal because of leap year
    System.out.println(LocalDate.of(2012, 12, 31));
    System.out.println(LocalDate.ofYearDay(2012, 365));
    // 
    LocalDate date1 = LocalDate.of(2016, Month.JANUARY, 1);
    LocalDateTime date2 = LocalDateTime.of(2017, Month.JUNE, 1, 1, 1);
    // Period p = Period.between(date2, date2); between localDates only!
    Period periodYMD = Period.of(1, 2, 1);
    LocalDate loc = LocalDate.of(2015, 1, 1);
    System.out.println(loc.plusDays(periodYMD.getDays()));
    // month, day of month
    MonthDay.of(10, 28);
    LocalDate loc1 = LocalDate.of(2015, 1, 27);
    LocalDate loc2 = LocalDate.of(2015, 1, 31);
    // System.out.println(Duration.between(loc1, loc2)); unsupported
    System.out.println(LocalDate.parse("2014-05-04").format(DateTimeFormatter.ISO_DATE));
    // .format(DateTimeFormatter.ISO_DATE_TIME));
    // java.time.temporal.UnsupportedTemporalTypeException: Unsupported field: HourOfDay
    // ------------------ IO Streams ------------------------------
    // console
    Console console = System.console();
    // input stream to read specific amount
    try (InputStream inputStream = new ByteArrayInputStream("abcdefghigklmn".getBytes(StandardCharsets.UTF_8.name()))) {
        byte[] buffer = new byte[10];
        int read = inputStream.read(buffer);
        System.out.println(read);
        for (byte c : buffer) {
            System.out.print((char) c);
        }
        System.out.println();
    } catch (IOException e) {
        e.printStackTrace();
    }
    // get owner
    Path path = Paths.get(".");
    try {
        BasicFileAttributes basicFileAttributes = Files.readAttributes(path, BasicFileAttributes.class);
        System.out.println(basicFileAttributes.size() + " " + basicFileAttributes.creationTime() + " " + basicFileAttributes.fileKey() + " " + basicFileAttributes.isDirectory() + " " + basicFileAttributes.isOther() + " " + basicFileAttributes.isRegularFile() + " " + basicFileAttributes.isSymbolicLink() + " " + basicFileAttributes.lastAccessTime() + " " + // no method getOwner
        basicFileAttributes.lastModifiedTime());
    } catch (IOException e) {
        e.printStackTrace();
    }
    try {
        // works!
        System.out.println(Files.getOwner(path));
    } catch (IOException e) {
        e.printStackTrace();
    }
    try {
        Map mp = Files.readAttributes(path, "*");
        // no owner
        System.out.println(mp);
    } catch (IOException e) {
        e.printStackTrace();
    }
    /*try {
            List<String> strings = Files.readAllLines(Paths.get("input.txt")); // not a stream
        } catch (IOException e) {
            e.printStackTrace(); // no such file exception
        }*/
    /*FileReader fr = new FileReader("new.txt"); // content ABCD
        System.out.println(fr.read()); // reads first character A to int 65
        fr.close();*/
    Path p1 = Paths.get("in\\new");
    Path p2 = Paths.get("file.txt");
    System.out.println(p1.resolve(p2));
    // ------------- Concurrency ----------------
    // atomic
    AtomicInteger atomicInteger = new AtomicInteger(10);
    System.out.println(atomicInteger.decrementAndGet());
    // executor with callable, runnable, future
    ExecutorService executorService = Executors.newFixedThreadPool(2);
    try {
        // executor service - may submit in the same thread thread.start - always new Thread
        Runnable runnable1 = () -> System.out.println("Runnable");
        Future<?> runnable = executorService.submit(runnable1);
        Callable<Integer> callable1 = () -> {
            System.out.println("Callable");
            return 1;
        };
        Future<Integer> callable = executorService.submit(callable1);
        // only runnable !
        executorService.execute(runnable1);
    } finally {
        executorService.shutdown();
    }
    // ----------------- interfaces, classes, etc. ------
    Equals.someMethod1();
    EqualsImpl.someMethod1();
    new EqualsImpl().someMethod();
    try (MyResource1 r1 = new MyResource1();
        MyResource2 r2 = new MyResource2()) {
        System.out.print("try ");
    } catch (Exception e) {
        // first is thrown others in the resource close are suppressed
        System.out.print("catch ");
        for (Throwable t : e.getSuppressed()) {
            System.out.println(t.getClass().getName());
        }
    }
}
Also used : IntStream(java.util.stream.IntStream) Arrays(java.util.Arrays) Date(java.util.Date) LocalDateTime(java.time.LocalDateTime) HashMap(java.util.HashMap) Callable(java.util.concurrent.Callable) TreeSet(java.util.TreeSet) ArrayList(java.util.ArrayList) Future(java.util.concurrent.Future) ByteArrayInputStream(java.io.ByteArrayInputStream) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) Locale(java.util.Locale) Map(java.util.Map) LocalTime(java.time.LocalTime) Console(java.io.Console) ZoneOffset(java.time.ZoneOffset) Path(java.nio.file.Path) DateFormat(java.text.DateFormat) ExecutorService(java.util.concurrent.ExecutorService) OffsetTime(java.time.OffsetTime) Period(java.time.Period) Files(java.nio.file.Files) Month(java.time.Month) MonthDay(java.time.MonthDay) IOException(java.io.IOException) BasicFileAttributes(java.nio.file.attribute.BasicFileAttributes) Collectors(java.util.stream.Collectors) StandardCharsets(java.nio.charset.StandardCharsets) Executors(java.util.concurrent.Executors) List(java.util.List) Stream(java.util.stream.Stream) TreeMap(java.util.TreeMap) Paths(java.nio.file.Paths) LongUnaryOperator(java.util.function.LongUnaryOperator) Closeable(java.io.Closeable) LocalDate(java.time.LocalDate) DateTimeFormatter(java.time.format.DateTimeFormatter) Optional(java.util.Optional) ArrayDeque(java.util.ArrayDeque) Comparator(java.util.Comparator) InputStream(java.io.InputStream) Locale(java.util.Locale) HashMap(java.util.HashMap) ArrayList(java.util.ArrayList) LocalDate(java.time.LocalDate) TreeSet(java.util.TreeSet) IntStream(java.util.stream.IntStream) ByteArrayInputStream(java.io.ByteArrayInputStream) Stream(java.util.stream.Stream) InputStream(java.io.InputStream) BasicFileAttributes(java.nio.file.attribute.BasicFileAttributes) Period(java.time.Period) ByteArrayInputStream(java.io.ByteArrayInputStream) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) HashMap(java.util.HashMap) Map(java.util.Map) TreeMap(java.util.TreeMap) LocalDateTime(java.time.LocalDateTime) Console(java.io.Console) Path(java.nio.file.Path) ByteArrayInputStream(java.io.ByteArrayInputStream) InputStream(java.io.InputStream) IOException(java.io.IOException) TreeMap(java.util.TreeMap) ArrayDeque(java.util.ArrayDeque) Date(java.util.Date) LocalDate(java.time.LocalDate) IOException(java.io.IOException) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) LongUnaryOperator(java.util.function.LongUnaryOperator) ExecutorService(java.util.concurrent.ExecutorService)

Example 75 with Period

use of java.time.Period in project knime-core by knime.

the class PeriodCellSerializer method deserialize.

@Override
public PeriodCell deserialize(final DataCellDataInput input) throws IOException {
    final int years = input.readInt();
    final int months = input.readInt();
    final int days = input.readInt();
    final Period period = Period.of(years, months, days);
    return new PeriodCell(period);
}
Also used : Period(java.time.Period)

Aggregations

Period (java.time.Period)110 Test (org.junit.Test)37 Test (org.testng.annotations.Test)27 LocalDate (java.time.LocalDate)21 UseDataProvider (com.tngtech.java.junit.dataprovider.UseDataProvider)8 Duration (java.time.Duration)8 LocalDateTime (java.time.LocalDateTime)7 ZonedDateTime (java.time.ZonedDateTime)7 DateTimeFormatter (java.time.format.DateTimeFormatter)6 Date (java.util.Date)6 Instant (java.time.Instant)5 LocalTime (java.time.LocalTime)5 ZoneId (java.time.ZoneId)5 Test (org.junit.jupiter.api.Test)5 DateTimeParseException (java.time.format.DateTimeParseException)4 TemporalAmount (java.time.temporal.TemporalAmount)4 Arrays (java.util.Arrays)4 List (java.util.List)4 Collectors (java.util.stream.Collectors)4 OffsetTime (java.time.OffsetTime)3