I have a php variable which contain date-time value like 2014-05-11 23:10:11 some times this may change, so i have to find it either it has date-time value or not, below is my variable
$my-variable='2014-08-26 18:25:47';
DateTime is a class in PHP. You should ask a different question if you want to validate a string. To validate a DateTime instance:
$my_variable instanceof DateTime
This should work for you to check if the string is a valid date time in your format:
<?php
$date = '2014-08-26 18:25:47';
function isTime($time) {
if (preg_match("/^([1-2][0-3]|[01]?[1-9]):([0-5]?[0-9]):([0-5]?[0-9])$/", $time))
return true;
return false;
}
$parts = explode(" ", $date);
list($y, $m, $d) = explode("-", $parts[0]);
if(checkdate($m, $d, $y) && isTime($parts[1]) ){
echo "OK";
} else {
echo "BAD";
}
?>
output:
OK
$my_variable='2014-08-26 18:25:47';
...
if ($my_variable instanceof DateTime) {
...
}
or
if (is_a($my_variable, 'DateTime')) {
...
}
If it's a string representing a date in time, you can use date_parse: http://php.net/manual/en/function.date-parse.php That will return an associative array with the parts of the date and time string if valid, FALSE if not.
If it's a date-time object, see the answer describing instanceOf.
Related
I am checking exception-dates against today’s date. If TRUE some code needs te be triggered…. but it always returns FALSE.
I’m certain that the output of both is in the exact same way (Y-m-d f.i. 2022-01-28). I even echoed both with good results.
I also believe both strings are real dates so why does the IF statement always returns FALSE??
function yl_opening_status_icon_shortcode() {
if (have_rows('booking_settings_exceptions', 'booking_settings')) {
while (have_rows('booking_settings_exceptions', 'booking_settings')) { the_row();
$today_date = date('Y-m-d'); // Today's date
$exceptions = get_sub_field('booking_settings_exceptions_date');
$exception = str_replace('/', '-', $exceptions);
$whole_day = get_sub_field('booking_settings_exceptions_whole_day');
$reason = get_sub_field('booking_settings_exceptions_reason');
$exception_dates = date("Y-m-d", strtotime($exception)); // Array of dates
if (in_array($today_date, $exception_dates)) {
// This always returns false, even if it's true
// echo $today_date and echo $exception_dates work and output does have same values
// and I believe there both set as real dates so why doesn't it pass here..?
}
}
}
return $output;
}
As it turned out, the exceptions weren't real dates after all. With this addition everything works great:
$exception_date = getDate($exception_dates);
Hi everyone I have an array
$dates = [2016-11-02,2016-11-05,2016-11-11,2016-11-15,2016-11-16]
in this I am getting all dates now I want to compare with $currentdate (2016-12-16) like this
if($dates <= $currentdate){
echo "true";
} else{
echo "false";
}
Any help will be much appreciated.
Not sure about other answers, but if you are trying to validate all the dates, please use the below code... Should work :)
$isLess = false;
$currentDate = Carbon::now();
foreach($dates as $data) {
if(Carbon::parse($date)->lte(currentDate)){
$isLess = true;
break;
}
}
echo $isLess;
Let me know in the comments if you face any problem :)
you can parse it to Carbon and use its comparison function
$date = Carbon::parse($date);
if($date->lte(Carbon::today())){
// your code
}
Here
lte() means less than equal to
to know more about Comparison operator of carbon visit http://carbon.nesbot.com/docs/#api-comparison
Since you're using Laravel, you can do that with Carbon:
if (Carbon::now()->gte(Carbon::parse($oneDate))
In one line (albeit not the prettiest)
if (collect(collect($dates)->filter(function($date) use($currentDate) { return Carbon::parse($date)->lte($currentDate); }))->count > 0) {
}
I have several date(strtotime) in a Variable and want the first nearest date that is after the specified date(my date) with php. what do i do?
Variable:
$varD = "1481691600,1482642000,1482037200";
my date:
1481778000 => (2016-12-15)
several date(strtotime):
1481691600 => (2016-12-14)
1482642000 => (2016-12-25)
1482037200 => (2016-12-18) //result
result:
1482037200 => (2016-12-18)
$varD = "1481691600,1482037200,1482642000";
$myDate = "1481778000";
After you explode the string of timestamps ($varD), you can filter them and return the minimum value of the result. Here is one way to do that using array_filter and min.
$comp = function($x) use ($myDate) { return $x > $myDate; };
$firstDateAfterYours = min(array_filter(explode(',', $varD), $comp));
But if you already know that the timestamps in the string will be in ascending order, it will probably be faster not to convert the whole thing to an array and sort through it. You can use strtok to go through it piece by piece and just stop as soon as you get to a timestamp larger than your target.
$ts = strtok($varD, ',');
while ($ts !== false) {
$ts = strtok(',');
if ($ts > $myDate) break;
}
$firstDateAfterYours = $ts;
I have been doing a project in php and i get a nested array from where i have to extract the values.
Here from this array i have to get only the time from the timestamp i.e from [ArrTime] and [DepTIme]
[Segment] => stdClass Object
(
[WSSegment] => stdClass Object
(
[DepTIme] => 2014-12-10T15:40:00
[ArrTime] => 2014-12-10T18:25:00
[ETicketEligible] => 1
[OperatingCarrier] => HW
)
)
I have being trying to apply the implode function on the timestamp but it is not working for me .
Try this one:
$DeptTime = date('H:i:s',strtotime($yourObject->Segment->WSSegment->DepTIme));
$ArrTime = date('H:i:s',strtotime($yourObject->Segment->WSSegment->ArrTime));
Write a function to retrieve it in php
<?php
$str = '2014-12-10T15:40:00';
function getOnlyTime($str = '') {
$time = '';
if (empty($str)) {
return $time;
}
return substr($str, 11);
}
echo getOnlyTime($yourObject->Segment->WSSegment->DepTIme);
echo getOnlyTime($yourObject->Segment->WSSegment->ArrTime);
?>
Live Example:
http://3v4l.org/1qChm
You could loop through the nested objects and see if the format matches a date. If it does, make an array of the matched elements. You could choose to index the array according to the index where it came from (if that matters later on in your code;
// Starts at "Segment"
foreach ($array as $segment => $item)
{
// Loops through the values of"WSSegment"
foreach ($item as $part => $value)
{
// Checks if the value is a valid date, might need to check type; $value must be a string
if ($date = date_create_from_format('Y-m-d\TH:i:s', $value))
{
// Dump to an array.
$dates[$part][] = $date;
}
}
}
$dates is now an array containing all valid dates in \DateTime format.
Here's another way that I recommend for several reasons. It saves one from having to manually extract the data by using substr() or explode(). The code uses two foreach loops to 'drill down to the desired items, namely the departure and arrival date-time data. If any of the names of the nested objects were to change, the code will still run since it makes use of variables in referring to those entities. Using a DateTime object's format property provides a handy way to access just the time information and you can easily exclude the seconds as the following example illustrates:
<?php
/**
* getTime()
* #param $str - date/time string
* returns time in hours and minutes
**/
function getTime( $str ){
$format = "H:i"; // Hours:Minutes
$timeObj = new DateTime( $str );
return $timeObj->format( $format );
}
foreach( $obj as $nested ) {
foreach( $nested as $n ){
echo 'DEP - ',getTime( $n->DepTime ),"\n";
echo 'ARV - ',getTime( $n->ArrTime ),"\n";
}
}
See http://3v4l.org/IdQN1
I need to add a zero to the date value that is posted as the MySQL date value will be used as a directory path to show added photos. Currently the directory is saved as 2012-2-5 and the MySQL entry is 2012-02-05.
I have tried the following, however it doesn't seem to be working:
$dates = array($_POST['photos_year'], $_POST['photos_month'], $_POST['photos_day']);
foreach($dates as $date) {
if (strlen($date) == 1) {
$date = '0' . $date;
}
}
$photos->date = $dates[0] . "-" . $dates[1] . "-" . $dates[2];
I am using a for loop to create the date form, it might be easier for me to edit this however I haven't had any success:
<select name="photos_month" id="photos_month" tabindex="3">
<option value ="">- Month -</option>
<?php
for($date=01;$date<=12;$date++) {
if (isset($photos) && $date==$month) {
echo "<option value='".$date."' selected='selected'>".$date."</option>";
} else {
echo "<option value='".$date."'>".$date."</option>";
}
}
?>
</select>
You need to update the foreach to be
foreach ($dates as &$date)
Currently, $date is a new symbol and will not overwrite the value. That should fix it, but it may be nice to have the correct strings in the options too. You can use str_pad to do that.
When doing a foreach, the element variable $date is a new variable, a copy of the value from the array. You should use a key and update the original array.
foreach($dates as $key => $date) {
if (strlen($date) == 1) {
$dates[$key] = '0' . $date;
}
}
Also, you're running that code on the year, you don't want to be adding a zero to the year, only the month and day.
You could make it a little simpler by just using sprintf with a format string;
$photos_year = '2012';
$photos_month = '2';
$photos_day = '5';
$result = sprintf("%4d-%02d-%02d", $photos_year, $photos_month, $photos_day);
// $result = '2012-02-05'
Check out the string pad function http://php.net/manual/en/function.str-pad.php
Along with the array map function http://php.net/manual/en/function.array-map.php
Using these two together would allow for you to go through each part of the date(array_map) and pad the value with a 0 (using str_pad)
Code would look something like this
$dates = array_map("padString",$dates);
function padString($string) {
return str_pad($string,2,"0",STR_PAD_LEFT);
}
print_r($dates);
//Gives you Array ( [0] => 2012 [1] => 02 [2] => 05 )
use sprintf()
For example:
$date = sprintf('%02d', $_POST['photos_day']);