2017-11-22 1 views
2

Javaの初心者です。Java:範囲(現在の日付/時刻からランダムな将来の日付(たとえば、現在の日付/時刻から5〜10日)までの範囲のランダムな日付を生成)

DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss"); 
Date date = new Date(); 
  1. 私は変数に上記現在の日付/時刻を配置するにはどうすればよい
  2. どのように私はRANDOM将来の日付を生成します:?私は、現在の日付/時刻を生成するために、私の意見で見つかっ方法現在の日付/時刻から(例えば、ランダムな範囲は5〜10日です)、これは私に修正がないことを意味します将来の日付の編集日。
  3. 将来の日付を変数に保存するにはどうすればよいですか?

サイドノート:私は質問1と3を尋ねなぜ比較および評価の目的のために両方の日付を保存する変数を使用することができるので、それはだ(のif-elseブロックで使用される)のための

おかげで多くのことをあなたの助け!

+1

をすでに変数に現在の日付を格納しています。 'new Date()'は現在の日付、 'Date date'は変数、' Date date = new Date(); 'は変数に現在の日付を格納しています。 –

+2

これまでに何をしてきたのですか? – assembler

答えて

4

代わりLocalDateTimeを使用することができます。

import java.time.format.DateTimeFormatter; 
import java.time.LocalDateTime; 
import java.util.Random; 

class Main { 
    public static void main(String[] args) { 
    // Declare DateTimeFormatter with desired format 
    DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy/MM/dd HH:mm:ss"); 

    // Save current LocalDateTime into a variable 
    LocalDateTime localDateTime = LocalDateTime.now(); 

    // Format LocalDateTime into a String variable and print 
    String formattedLocalDateTime = localDateTime.format(dateTimeFormatter); 
    System.out.println("Current Date: " + formattedLocalDateTime); 

    //Get random amount of days between 5 and 10 
    Random random = new Random(); 
    int randomAmountOfDays = random.nextInt(10 - 5 + 1) + 5; 
    System.out.println("Random amount of days: " + randomAmountOfDays); 

    // Add randomAmountOfDays to LocalDateTime variable we defined earlier and store it into a new variable 
    LocalDateTime futureLocalDateTime = localDateTime.plusDays(randomAmountOfDays); 

    // Format new LocalDateTime variable into a String variable and print 
    String formattedFutureLocalDateTime = futureLocalDateTime.format(dateTimeFormatter); 
    System.out.println("Date " + randomAmountOfDays + " days in future: " + formattedFutureLocalDateTime); 
    } 
} 

出力例:

Current Date: 2017/11/22 20:41:03 
Random amount of days: 7 
Date 7 days in future: 2017/11/29 20:41:03 
+1

ニース。要求どおりにすべてがうまく変数に格納されます。そして、コメントでうまく説明しました。 –

関連する問題