php를 사용하여 두 날짜 사이에 임의의 날짜를 생성하는 방법은 무엇입니까?
두 개의 고정 타임스탬프 사이에 임의의 날짜를 할당해야 하는 응용 프로그램을 코딩하는 중입니다.
내가 먼저 검색한 php를 사용하여 이것을 달성할 수 있는 방법은 php가 아니라 자바에 대한 답만 찾았습니다.
예:
$string = randomdate(1262055681,1262055681);
PHP에는 란드() 함수가 있습니다.
$int= rand(1262055681,1262055681);
또한 mt_rand()를 가지며, 이는 일반적으로 결과에서 더 나은 무작위성을 갖는 것으로 알려져 있습니다.
$int= mt_rand(1262055681,1262055681);
타임스탬프를 문자열로 만들려면 date()를 사용합니다. 즉, 다음과 같습니다.
$string = date("Y-m-d H:i:s",$int);
지정된 날짜가 날짜 시간 형식인 경우 이 방법을 사용하는 가장 쉬운 방법은 두 숫자를 타임스탬프로 변환한 다음 임의의 숫자 생성기에 대한 최소 및 최대 경계로 설정하는 것입니다.
간단한 PHP 예는 다음과 같습니다.
// Find a randomDate between $start_date and $end_date
function randomDate($start_date, $end_date)
{
// Convert to timetamps
$min = strtotime($start_date);
$max = strtotime($end_date);
// Generate random number using above bounds
$val = rand($min, $max);
// Convert back to desired date format
return date('Y-m-d H:i:s', $val);
}
이 함수는 zombat에서 제안한 strtotime()을 사용하여 날짜 시간 설명을 Unix 타임스탬프로 변환하고 date()를 사용하여 생성된 임의의 타임스탬프로 유효한 날짜를 만듭니다.
PHP를 사용하는 다른 솔루션
$start
그리고.$end
개체이며 타임스탬프로 변환합니다.그런 다음 방법을 사용하여 임의의 타임스탬프를 가져옵니다.마지막으로 우리는 객체를 다시 만듭니다.
function randomDateInRange(DateTime $start, DateTime $end) {
$randomTimestamp = mt_rand($start->getTimestamp(), $end->getTimestamp());
$randomDate = new DateTime();
$randomDate->setTimestamp($randomTimestamp);
return $randomDate;
}
임의의 숫자를 사용하여 임의의 날짜를 결정할 수 있습니다.날짜 사이에 0에서 일 사이의 임의 숫자를 가져옵니다.그러면 첫 번째 날짜에 그 숫자를 추가하면 됩니다.
예를 들어, 날짜를 가져오는 경우 현재 날짜와 30일 사이의 임의 숫자입니다.
echo date('Y-m-d', strtotime( '+'.mt_rand(0,30).' days'));
다음은 또 다른 예입니다.
$datestart = strtotime('2009-12-10');//you can change it to your timestamp;
$dateend = strtotime('2009-12-31');//you can change it to your timestamp;
$daystep = 86400;
$datebetween = abs(($dateend - $datestart) / $daystep);
$randomday = rand(0, $datebetween);
echo "\$randomday: $randomday\n";
echo date("Y-m-d", $datestart + ($randomday * $daystep)) . "\n";
가장 좋은 방법:
$timestamp = rand( strtotime("Jan 01 2015"), strtotime("Nov 01 2016") );
$random_Date = date("d.m.Y", $timestamp );
$startDate = Carbon::now();
$endDate = Carbon::now()->subDays(7);
$randomDate = Carbon::createFromTimestamp(rand($endDate->timestamp, $startDate->timestamp))->format('Y-m-d');
OR
$randomDate = Carbon::now()->subDays(rand(0, 7))->format('Y-m-d');
date_format을 사용할 수 있는 다른 솔루션:
/**
* Method to generate random date between two dates
* @param $sStartDate
* @param $sEndDate
* @param string $sFormat
* @return bool|string
*/
function randomDate($sStartDate, $sEndDate, $sFormat = 'Y-m-d H:i:s') {
// Convert the supplied date to timestamp
$fMin = strtotime($sStartDate);
$fMax = strtotime($sEndDate);
// Generate a random number from the start and end dates
$fVal = mt_rand($fMin, $fMax);
// Convert back to the specified date format
return date($sFormat, $fVal);
}
출처: https://gist.github.com/samcrosoft/6550473
예를 들어 다음을 사용할 수 있습니다.
$date_random = randomDate('2018-07-09 00:00:00','2018-08-27 00:00:00');
의 양strtotime
여기는 너무 높아요.
1971년 이전과 2038년 이후에 관심이 있는 사람들을 위해, 여기 현대적이고 유연한 솔루션이 있습니다.
function random_date_in_range( $date1, $date2 ){
if (!is_a($date1, 'DateTime')) {
$date1 = new DateTime( (ctype_digit((string)$date1) ? '@' : '') . $date1);
$date2 = new DateTime( (ctype_digit((string)$date2) ? '@' : '') . $date2);
}
$random_u = random_int($date1->format('U'), $date2->format('U'));
$random_date = new DateTime();
$random_date->setTimestamp($random_u);
return $random_date->format('Y-m-d') .'<br>';
}
여러 가지 방법으로...
// timestamps
echo random_date_in_range(157766400,1489686923);
// any date string
echo random_date_in_range('1492-01-01','2050-01-01');
// English textual parsing
echo random_date_in_range('last Sunday','now');
// DateTime object
$date1 = new DateTime('1000 years ago');
$date2 = new DateTime('now + 10 months');
echo random_date_in_range($date1, $date2);
이 기능은 다음을 필요로 합니다.date1
<=date2
.
저는 이전에도 같은 상황이 있었고 위의 답변 중 어떤 것도 제 문제를 해결하지 못했습니다.
새로운 기능과 함께 제공됨
function randomDate($startDate, $endDate, $count = 1 ,$dateFormat = 'Y-m-d H:i:s')
{
//inspired by
// https://gist.github.com/samcrosoft/6550473
// Convert the supplied date to timestamp
$minDateString = strtotime($startDate);
$maxDateString = strtotime($endDate);
if ($minDateString > $maxDateString)
{
throw new Exception("From Date must be lesser than to date", 1);
}
for ($ctrlVarb = 1; $ctrlVarb <= $count; $ctrlVarb++)
{
$randomDate[] = mt_rand($minDateString, $maxDateString);
}
if (sizeof($randomDate) == 1)
{
$randomDate = date($dateFormat, $randomDate[0]);
return $randomDate;
}elseif (sizeof($randomDate) > 1)
{
foreach ($randomDate as $randomDateKey => $randomDateValue)
{
$randomDatearray[] = date($dateFormat, $randomDateValue);
}
//return $randomDatearray;
return array_values(array_unique($randomDatearray));
}
}
이제 테스트 파트(테스트 중 데이터가 변경될 수 있음)
$fromDate = '2012-04-02';
$toDate = '2018-07-02';
print_r(랜덤Date($fromDate,$toDate,1));
결과는 다음과 같습니다.
2016-01-25 11:43:22
print_r(랜덤Date($fromDate,$toDate,1));
array:10 [▼
0 => "2015-08-24 18:38:26"
1 => "2018-01-13 21:12:59"
2 => "2018-06-22 00:18:40"
3 => "2016-09-14 02:38:04"
4 => "2016-03-29 17:51:30"
5 => "2018-03-30 07:28:48"
6 => "2018-06-13 17:57:47"
7 => "2017-09-24 16:00:40"
8 => "2016-12-29 17:32:33"
9 => "2013-09-05 02:56:14"
]
하지만 몇 번의 테스트 후에 저는 입력이 그렇다면 어떨까 생각했습니다.
$fromDate ='2018-07-02 09:20:39';
$toDate = '2018-07-02 10:20:39';
따라서 다음과 같은 많은 날짜를 생성하는 동안 중복이 발생할 수 있습니다.10,000
그래서 추가했습니다.array_unique
되지 않은 됩니다.
만약 당신이 라벨을 사용한다면 그것은 당신을 위한 것입니다.
\Carbon\Carbon::now()->subDays(rand(0, 90))->format('Y-m-d');
가장 간단한 것은, 이 작은 기능이 나에게 효과가 있다는 것입니다. 나는 그것을 도우미 수업에서 썼습니다.datetime
인
/**
* Return date between two dates
*
* @param String $startDate
* @param String $endDate
* @return String
*
* @author Kuldeep Dangi <kuldeepamy@gmail.com>
*/
public static function getRandomDateTime($startDate, $endDate)
{
$randomTime = mt_rand(strtotime($startDate), strtotime($endDate));
return date(self::DATETIME_FORMAT_MYSQL, $randomTime);
}
꽤 좋은 질문입니다. 앱을 위한 무작위 샘플 데이터를 생성해야 합니다.
다음 함수를 선택적 인수와 함께 사용하여 임의 날짜를 생성할 수 있습니다.
function randomDate($startDate, $endDate, $format = "Y-M-d H:i:s", $timezone = "gmt", $mode = "debug")
{
return $result;
}
샘플 입력:
echo 'UTC: ' . randomDate("1942-01-19", "2016-06-03", "Y-M-d H:i:s", "utc") . '<br>';
//1942-Jan-19 07:00:00
echo 'GMT: ' . randomDate("1942-01-19", "2016-06-03", "Y/M/d H:i A", "gmt") . '<br>';
//1942/Jan/19 00:00 AM
echo 'France: ' . randomDate("1942-01-19", "2016-06-03", "Y F", "Europe/Paris") . '<br>';
//1942 January
echo 'UTC - 4 offset time only: ' . randomDate("1942-01-19", "2016-06-03", "H:i:s", -4) . '<br>';
//20:00:00
echo 'GMT +2 offset: ' . randomDate("1942-01-19", "2016-06-03", "Y-M-d H:i:s", 2) . '<br>';
//1942-Jan-19 02:00:00
echo 'No Options: ' . randomDate("1942-01-19", "2016-06-03") . '<br>';
//1942-Jan-19 00:00:00
판독기 요구 사항은 앱마다 다를 수 있습니다. 일반적으로 이 기능이 응용 프로그램에 대한 임의의 날짜/샘플 데이터를 생성해야 하는 편리한 도구이기를 바랍니다.
이 기능은 처음에는 디버그 모드이므로 다음으로 변경하십시오.$mood=""
운영 중인 디버그를 제외하고.
이 기능은 다음을 허용합니다.
- 시작일
- 종료일
- format: 날짜 또는 시간에 대해 허용되는 모든 php 형식
- 표준시: 이름 또는 오프셋 번호
- 모드: 디버그, epoch, verbose epoch 또는 verbose epoch
debug not 모드의 출력은 선택 사양에 따라 난수입니다.
PHP 7.x로 테스트됨
// Find a randomDate between $startDate and $endDate
function randomDate($startDate, $endDate)
{
// Convert to timetamps
$min = strtotime($startDate);
$max = strtotime($endDate);
// Generate random number using above bounds
$val = rand($min, $max);
// Convert back to date
return Carbon::createFromTimestamp($val);
}
dd($this->randomDate('2014-12-10', Carbon::now()->toString()));
탄소 사용
$yeni_tarih = date('Y-m-d', strtotime( '+'.mt_rand(-90,0).' days'))." ".date('H', strtotime( '+'.mt_rand(0,24).' hours')).":".rand(1,59).":".rand(1,59);
전체 임의 날짜 및 시간
언급URL : https://stackoverflow.com/questions/1972712/how-to-generate-random-date-between-two-dates-using-php
'programing' 카테고리의 다른 글
python 사전에서 속성 설정 (0) | 2023.07.26 |
---|---|
개체의 속성 이름을 가져오는 중 (0) | 2023.07.26 |
다국어 데이터베이스 설계를 위한 모범 사례는 무엇입니까? (0) | 2023.07.26 |
표에 날짜 열이 없는 경우 MariaDB에서 최근 30일 레코드 양식 표를 찾는 방법 (0) | 2023.07.26 |
node.js와 Python의 결합 (0) | 2023.07.26 |