2016-03-29 28 views

Odpowiedz

3

Z Java manipulacja 8 LOCALDATE jest tak proste, jak:

LocalDate.now().plusDays(2) 

Nie jestem pewien, co TimeCategory zyskałaby cię?


można siekać go do metaklasą z LOCALDATE i LocalDatTime dość prosto:

import groovy.time.* 
import java.time.* 

LocalDate.metaClass { 
    plus { Duration d -> 
     delegate.plusYears(d.years) 
       .plusMonths(d.months) 
       .plusDays(d.days) 
    } 
} 

LocalDateTime.metaClass { 
    plus { Duration d -> 
     delegate.plusYears(d.years) 
       .plusMonths(d.months) 
       .plusDays(d.days) 
       .plusHours(d.hours) 
       .plusMinutes(d.minutes) 
       .plusSeconds(d.seconds) 
    } 
} 

use(TimeCategory) { 
    LocalDateTime.now() + 4.days 
} 
+0

Zobacz mój komentarz powyżej. Chodzi o czytelność i moją grupę docelową, która nie jest biegła w Javie. – Pierre

+1

@Pierre Możesz dodać obsługę LD i LDT bez zbytniego wysiłku ... patrz edycja –

+0

Idealnie! Wciąż nie przyzwyczajony do dynamicznej natury groovy i jest to świetny przykład dodawania niestandardowego wsparcia do zewnętrznych, a nawet końcowych klas! – Pierre

2

trywialny przykład byłoby:

import groovy.time.TimeCategory 
import java.time.LocalDate 
import java.time.LocalDateTime 

use(TimeCategory) { 
    println Date.parse('yyyy-MM-dd', LocalDate.now().toString()) + 4.hours 
    println Date.parse("yyyy-MM-dd'T'hh:mm:ss", LocalDateTime.now().toString()) - 4.hours 
} 
+0

Czy nie ma natywne wsparcie dla java8 jednostkach czasowych? Podany przykład, mimo że jest poprawny, jest sposobem na pełne rozwikłanie i dosłownie zabija punkt korzystania z TimeCategory. – Pierre

+1

Nie, nie ma żadnych. Zgadzam się, to jest pełne gadatliwości. Jeśli szukasz manipulacji czasem, LocalDateTime i LocalDate API ma już metody takie jak 'plusHours()'. Czy to jest coś, czego szukasz? – dmahapatro

+0

Tak. Java jest silna we mnie :) i w pełni świadoma wszystkich lokalnych funkcji manipulowania datą i czasem. Istnieje jednak pewna czytelność, którą TimeCategory zapewnia odwołującym się do moich docelowych odbiorców (QA), która jest po prostu lepsza. Myślę, że po prostu będę po prostu czas java8 bezpośrednio – Pierre

2

Ja też byłem rozczarowany, że TimeCategory deklaruje swój własny czas i nie jest Java 8 obsłudze. Skłoniło mnie to do napisania trochę mojego własnego kodu, który według mnie byłby istotny dla tego pytania. Jest skupiony wokół ZonedDateTime w przeciwieństwie do LocalDateTime, ponieważ interesowałem się logiką TimeZone, w której go używam. Nie jest on tak kompletny jak klasa groovy.time.TimeCategory i ma tylko kilka operacji, które mnie interesowały, więc możesz do niego dodać.

Bez zbędnych ceregieli:

import java.time.Duration 
import java.time.ZoneOffset 
import java.time.ZonedDateTime 
import java.time.format.DateTimeFormatter 
import java.time.temporal.ChronoUnit 

class TimeCategory { 
    static getDays(Integer self) { Duration.ofDays self } 
    static getHours(Integer self) { Duration.ofHours self } 
    static getMillis(Integer self) { Duration.ofMillis self } 
    static getMinutes(Integer self) { Duration.ofMinutes self } 
    static getNanos(Integer self) { Duration.ofNanos self } 
    static getSeconds(Integer self) { Duration.ofSeconds self } 
    static getWeeks(Integer self) { Duration.ofDays self * 7 } 
    static getDay(Integer self) { Duration.ofDays self } 
    static getHour(Integer self) { Duration.ofHours self } 
    static getMilli(Integer self) { Duration.ofMillis self } 
    static getMinute(Integer self) { Duration.ofMinutes self } 
    static getNano(Integer self) { Duration.ofNanos self } 
    static getSecond(Integer self) { Duration.ofSeconds self } 
    static getWeek(Integer self) { Duration.ofDays self * 7 } 
    static ZonedDateTime getAgo(Duration self) { ZonedDateTime.now() - self } 
    static ZonedDateTime getUtc(ZonedDateTime self) { self.withZoneSameInstant(ZoneOffset.UTC) } 
    static ZonedDateTime getLocal(ZonedDateTime self) { self.withZoneSameInstant(ZoneOffset.systemDefault()) } 
    static ZonedDateTime getNow() { ZonedDateTime.now() } 
    static Duration minus(ZonedDateTime self, ZonedDateTime other) { Duration.between(self, other) } 
    static BigInteger getTotalNanos(Duration self) { self.seconds.toBigInteger() * 10 ** 9 + self.nano } 
    static String toString(ZonedDateTime self, String pattern) { self.format(DateTimeFormatter.ofPattern(pattern)) } 
    static Duration mod(Duration self, Duration other) { 
     def (long seconds, int nanos) = (self.totalNanos % other.totalNanos).divideAndRemainder(10g.pow(9)) 
     Duration.ofSeconds(seconds) + nanos.nanos 
    } 

    static load() { 
     Integer.mixin(TimeCategory) 
     ZonedDateTime.mixin(TimeCategory) 
     Duration.mixin(TimeCategory) 
    } 
} 

Przykład wykorzystania:

// I prefer putting this in a start-up location and pollute the namespace rather than use 
// `use() {...}` 
TimeCategory.load() 

// Construct readable java 8 durations 
Duration d = 1.day + 2.hours + 3.minutes - 4.seconds 

// Easily construct dates relative to now 
ZonedDateTime yesterday = 1.day.ago 

// Of course, you can still call "unsugared" functions like truncatedTo for rounding down 
ZonedDateTime today = TimeCategory.now.truncatedTo(ChronoUnit.DAYS) 

// Converting between local and utc doesn't change the underlying instant 
assert 0.seconds == yesterday.utc - yesterday.local 

// Modulo arithmetic. Cool! 
assert 1.minute % 17.seconds == 9.seconds 

// Slightly cleaner date formatting 
println "Today in strange format ${today.toString('dd/yy/MM')}" 
+0

Dzięki ! zdecydowanie przydatny kod do obejrzenia. – Pierre

+0

W jaki sposób zmodyfikowałbyś to, aby obsługiwać .from.now, tak jak domyślna kategoria czasu? – Ali