2013-02-09 3 views
2

Joda-Time 시드 포인트를 만들려고합니다. 달성하고자하는 것은 Joda-Time에서 시드 datetime을 제공한다는 것입니다.이 경우 이 datetime2보다 이전 인 두 개의 다른 임의의 datetime을 생성해야하며이 datetime은 해당 특정 시간의 시드 포인트에만 값을 생성합니다.joda 시간을 사용하여 시드 한 후 비교하십시오.

time- 18:00:00 followed by date-2013-02-13 

Random1 - 2013-02-13 18:05:24 

Random2 - 2013-02-13 18:48:22 

하나의 DB에서 시간을 받고 사용자가 날짜를 선택했습니다. 지정된 형식으로 두 번 무작위로 생성해야합니다. 분과 초만 변경되며 다른 것은 수정되지 않습니다.

이것이 가능합니까? 이것을 어떻게 할 수 있습니까?

답변

1

다음 코드는 원하는대로 수행해야합니다. 시드 시간의 분 또는 초가 0이 아닌 경우 .parseDateTime(inputDateTime) 메서드 호출 후에 .withMinuteOfHour(0).withSecondOfMinute(0)을 추가해야합니다.

import java.util.Random; 
import org.joda.time.DateTime; 
import org.joda.time.format.DateTimeFormat; 
import org.joda.time.format.DateTimeFormatter; 

public class RandomTime { 

DateTimeFormatter inputFormat = DateTimeFormat.forPattern("HH:mm:ss yyyy-MM-dd"); 
DateTimeFormatter outputFormat = DateTimeFormat.forPattern("yyyy-MM-dd HH:mm:ss"); 

public TwoRandomTimes getRandomTimesFromSeed(String inputDateTime) { 
    DateTime seed = inputFormat.parseDateTime(inputDateTime); 
    Random random = new Random(); 
    int seconds1 = random.nextInt(3600); 
    int seconds2 = random.nextInt(3600 - seconds1); 

    DateTime time1 = new DateTime(seed).plusSeconds(seconds1); 
    DateTime time2 = new DateTime(time1).plusSeconds(seconds2); 
    return new TwoRandomTimes(time1, time2); 
} 

public class TwoRandomTimes { 
    public final DateTime random1; 
    public final DateTime random2; 

    private TwoRandomTimes(DateTime time1, DateTime time2) { 
     random1 = time1; 
     random2 = time2; 
    } 

    @Override 
    public String toString() { 
     return "Random1 - " + outputFormat.print(random1) + "\nRandom2 - " + outputFormat.print(random2); 
    } 
} 

public static void main(String[] args) { 
    RandomTime rt = new RandomTime(); 
    System.out.println(rt.getRandomTimesFromSeed("18:00:00 2013-02-13")); 
} 
} 

이 솔루션에서 첫 번째 임의 시간은 실제로 두 번째 임의 시간의 하한으로 사용됩니다. 다른 해결책은 두 개의 무작위 날짜를 얻은 다음 정렬하는 것입니다.

+0

믿을 수없는 직업, second1을 뺀 시간 2를 얻으려는 사람에게 감사드립니다. 내 마음을 치지 않았습니다. 고맙습니다. – chettyharish

+0

@cheifulharish 제 기쁨. :) 코너 케이스와 오프 바이 한 오류에 대한 구현을 확인하십시오. 예를 들어 첫 번째 시간이 18:59:59 인 경우 특히 임의의 시간이 동일 할 수 있습니다. – ZeroOne

0

나는 아마 다음과 같이 갈 것이다 :

final Random r = new Random(); 
final DateTime suppliedDate = new DateTime(); 
final int minute = r.nextInt(60); 
final int second = r.nextInt(60); 

final DateTime date1 = new DateTime(suppliedDate).withMinuteOfHour(minute).withSecondOfMinute(second); 
final DateTime date2 = new DateTime(suppliedDate).withMinuteOfHour(minute + r.nextInt(60 - minute)).withSecondOfMinute(second + r.nextInt(60 - second)); 

suppliedDate가 데이터베이스에서 날짜라고 가정. 그런 다음 시드 시간을 기준으로 임의의 분 및 초로 두 개의 새로운 시간을 생성합니다. 또한 계산 된 난수의 범위를 변경하여 두 번째 시간이 처음 이후임을 보장합니다.

관련 문제