LoginSignup
1
2

More than 5 years have passed since last update.

オーバーフローに気をつけよう

Last updated at Posted at 2016-09-23

時刻の計算をしている時に、つい失敗したので共有。

問題

下のプログラム、どこに間違いがあるか?

OverflowSample.java
class OverflowSample {
    public static void main(String[] args) {
        /* 現在時刻をミリ秒で表示 */
        System.out.println(System.currentTimeMillis());
        /* 現在時刻の30日前をミリ秒で表示 */
        System.out.println(System.currentTimeMillis() - 1000 * 60 * 60 * 24 * 30);
    }
}
$ java OverflowSample
1474654212417
1476357179713  ← あれ? 引き算したのに増えている?!

原因

「30日前のミリ秒」がintの範囲を超えています(オーバーフロー)。

1000 * 60 * 60 * 24 * 30 → -1702967296

解答

オーバーフローする計算結果をlongに変換しておきます。

OverflowSample.java
class OverflowSample {
    public static void main(String[] args) {
        /* 現在時刻をミリ秒で表示 */
        System.out.println(System.currentTimeMillis());
        /* 現在時刻の30日前をミリ秒で表示 */
        System.out.println(System.currentTimeMillis() - 1000L * 60 * 60 * 24 * 30);
    }
}
$ java OverflowSample
1474654536537
1472062536537 ← チャンと引かれている

メデタシ、メデタシ。

1
2
1

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
1
2