0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

Joda-Timeで固定の現在時刻を返す

Last updated at Posted at 2022-09-25

例えば、ユニットテストで現在時刻返すメソッドを固定日付で返したい、などのケースがある。

implementation 'joda-time:joda-time:2.11.1'
import org.joda.time.DateTime;
import org.joda.time.DateTimeUtils;

public class JodaTImeSsample {
  public static void main(String[] args) {

    DateTimeUtils.setCurrentMillisFixed(DateTime.parse("2010-06-30T01:20").getMillis());
    DateTime now = DateTime.now();
    System.out.println(now); // 2010-06-30T01:20:00.000+09:00

    DateTimeUtils.setCurrentMillisSystem(); // 現在時刻を返すようにリセット
  }
}

DateTimeUtils.setCurrentMillisFixedは下記のようにstatic変数を書き換える。volatile付いてるとはいえ、マルチスレッドで何度も書き換えるのはちょっと怖い。ユニットテストを平行に実行しなければ問題は無い……とは思うが。

    private static volatile MillisProvider cMillisProvider = SYSTEM_MILLIS_PROVIDER;

    public static final void setCurrentMillisFixed(long fixedMillis) throws SecurityException {
        checkPermission();
        cMillisProvider = new FixedMillisProvider(fixedMillis);
        ...

新規にJoda-Time使うことは無いと思われるが、既存部分についてはやはり後発のjava.time.Clockを使う方が良いだろう。

import java.time.Clock;
import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneId;

public class JodaTImeSsample {
  public static void main(String[] args) {
    Clock c = Clock.fixed(Instant.parse("2007-12-03T10:15:30.00+09:00"), ZoneId.systemDefault());
    LocalDateTime now = LocalDateTime.now(c);
    System.out.println(now); // 2007-12-03T10:15:30

  }
}

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?