2017-11-22 5 views
2

자바 초보자 여기를 클릭하고 검색하면 연구가 가장 좋습니다 방법 나는 현재 날짜/시간을 생성하는 제 생각에 발견 : 나는 변수에 위의 현재 날짜/시간을 배치하려면 어떻게Java : 범위 (현재 날짜/시간에서 임의의 미래 날짜 (예 : 현재 날짜/현재 시간에서 5-10 일) 범위의 임의의 날짜 생성)

DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss"); 
Date date = new Date(); 
  1. 을 나는 RANDOM 미래의 날짜를 생성하려면 어떻게
  2. 을 현재 날짜/시간 (예 : 임의의 범위는 5 ~ 10 일) 일 수 있습니다. 즉, 수정이 필요하지 않습니다. 미래 날짜의 편집 날짜.
  3. 미래의 날짜을 변수에 어떻게 저장합니까?

사이드 참고 : 나는 질문 1과 3 묻는 이유는 무엇

고마워 대한 (있는 경우 - 다른 블록에 사용) 비교 및 ​​평가 목적을 위해 모두 날짜를 저장하는 변수를 사용할 수 있습니다 때문입니다 당신의 도움!

+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

니스. 모든 것은 요청에 따라 변수에 잘 저장됩니다. 그리고 주석에 잘 설명되어 있습니다. –