Generating Random Date and Time with PHP
Actually title tells everything. Firstly I want to show you how you can generate random date.
<?php
$timestamp = mt_rand(1, time());
$randomDate = date('Y-m-d', $timestamp);
echo $randomDate;
In this way it will be created a random date since 1970. Let keep this in pocket and let's try to generate a date between two specified date.
<?php
$start = strtotime('2018-01-01');
$end = time();
$timestamp = mt_rand($start, $end);
echo date('Y-m-d', $timestamp);
In the example above it will create a date from 1/1/2018 to present day. I indicated the 2.date as present but you may write strtotime()
and include a specific a date for 2.date.
Also if you want to show the time with date use date()
function in this way;
echo date('Y-m-d H:i:s', $timestamp);
Let's look how can we generate random time. We create a random number between 1 and 86400. 86400=24hour X 60min X 60sec
<?php
$start = 1;
$end = 60 * 60 * 24;
$timestamp = mt_rand($start, $end);
echo date('H:i:s', $timestamp);
Maybe you may say what i can do with this? Don't worry when the time came it will be a information that you will enjoy when you are learning :) Why did it work for me? For a project i had to enter a dummy data and to create weekly, monthly, yearly charts, these data had to be entered on random dates.In this way I created dummy datas by creating random dates, and it worked for me today, let's see tomorrow which one of you will handle your job with this? :)
Comments
Popular Articles
Popular Tags
- #directive
- #Function
- #React
- #Class
- #centOS
- #Json
- #Text
- #API
- #URL
- #Encrypting
- #Redirect
- #Form
- #Special Characters
- #Special
- #Random
- #Generating
- #SASS
- #Version
- #Installation
- #Show
- #
- #Ajax
- #method
- #Logic For Displaying Posts
- #Key
- #DDOS
- #Default Value
- #Comment Line
- #1364 Field
- #Error
- #Abbreviation
- #QR Code Generating
- #Date
- #timeAgo
- #cURL
- #Array
- #Arrays with Key Values to String Statement
- #Short Tag
- #Vite
- #Reading Excel Files
- #Activate
- #Reading
- #Composer
- #Autoloader
- #PSR-4
- #Insert
- #Record
- #Real Time
- #Characters
- #Socket.io
There are no comments, make the firs comment