2016-03-29 5 views
5

javaC LocalDateとLocalDateTimeでTimeCategory(または同等のもの)を使用する方法の例や参考資料はありますか?私が見つけたすべてのコードスニペットは、私が避けようとしているjava.util.Dateを参照しています。LocalDateとLocalDateTimeを持つGroovyのTimeCategory

答えて

3

のJava 8 LOCALDATE操作は、のような単純なものでは:私はTimeCategoryはあなたを得るだろうかわからないんだけど

LocalDate.now().plusDays(2) 


あなたは非常に単純LOCALDATEとLocalDatTimeのメタクラスにして、それをハックすることができます

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

上記の私のコメントを参照してください。私はJavaをあまり使い慣れていません。 – Pierre

+1

@Pierreあまりにも面倒なくLDとLDTにサポートを追加することができます...編集 –

+0

パーフェクト! Groovyの動的な性質にまだ慣れていないこれは、外部クラスや最終クラスへのカスタムサポートを追加する素晴らしい例です! – Pierre

2

簡単な例は次のようになります。

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

がjava8時間エンティティのためのネイティブサポートはありませんか?あなたが示している例は有効ですが、冗長であり、文字通りTimeCategoryを使用するポイントを殺します。 – Pierre

+1

いいえ、それは何も持っていません。私はそれが冗長であることに同意します。時間の操作を探しているならば、LocalDateTimeとLocalDate APIはすでに 'plusHours()'のようなメソッドを持っています。それはあなたが探しているものですか? – dmahapatro

+0

はい。 Javaは私の中で強く:)すべての現地の日時操作機能を完全に認識しています。しかし、TimeCategoryが私のターゲットオーディエンス(QAs)にぴったりのものを提供するという、ある程度の読みやすさがあります。私はちょうどちょうどちょうどjava8時間になると思います – Pierre

2

私もTimeCategoryが、それは自身の期間だとJava 8友好的ではない宣言されていることを失望しました。これは、私がこの質問に関連すると思っていた自分のコードを少し書くようになった。 LocalDateTimeではなく、ZonedDateTimeに注目しています。なぜなら、私が使っているTimeZoneロジックに興味があったからです。それはgroovy.time.TimeCategoryクラスとほぼ同じくらい完全ではなく、私が興味を持っていたほんの一握りの操作しかないので、自由に追加してください。さらに騒ぎがなければ

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) 
    } 
} 

使用例:

// 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

ありがとう!間違いなく役に立つコードです。 – Pierre

+0

デフォルトのTimeCategoryのように.from.nowをサポートするにはどうすればよいでしょうか? – Ali

関連する問題