how to convert String time to dateTime format in php? - php

I want to check who is greater datetime between two datetime variables.
I have an string of datetime and i want to convert it into datetime format and check it who is greater?
my variables:
$d1 = '2016-02-02 07:35:00';
$d2 = '2016-02-1 13:10:31';
and I want to check who is greater between above two variables.
if($d1>$d2)
{
return true;
}

There are comparison operators for the DateTime class in php . Something like this :
date_default_timezone_set('Europe/London');
$d1 = new DateTime('2008-08-03 14:52:10');
$d2 = new DateTime('2008-01-03 11:11:10');
var_dump($d1 == $d2);
var_dump($d1 > $d2);
var_dump($d1 < $d2);
Output
bool(false)
bool(true)
bool(false)

Use strtotime()
$d1 = strtotime('2016-02-02 07:35:00');
$d2 = strtotime('2016-02-1 13:10:31');
if($d1>$d2){
return true;
}

You can use DateTime
if (new DateTime($d1) > new DateTime($d2) {
return true;
}

Try strtotime() function like this :
if(strtotime($d1) > strtotime($d2))
{
return true;
}

try this
$d1 = strtotime('2016-02-02 07:35:00');
$d2 = strtotime('2016-02-1 13:10:31');
if($d1 > $d2)
{
return true;
}

You can compare like that:
<?
$d1 = '2016-02-02 07:35:00';
$d2 = '2016-02-1 13:10:31';
$ts1 = strtotime($d1); // 1454394900
$ts2 = strtotime($d2); // 1454328631
if($ts1>$ts2) // 1454394900 > 1454328631 = true
{
echo 1; // return this.
}
else{
echo 0;
}
?>
Use strtotime() for both date and than compare.

<?php
$date = '1994-04-27 11:35:00';
$date1 = '2016-02-10 13:10:31';
$stt = strtotime($date); // 767439300
$stt1 = strtotime($date1); // 1455106231
if($stt>$stt1)
echo 1;
else
echo 0;
?>
use strtotime function to convert string to time formate...

Related

Retrieve date format and parse if needed in PHP

I've created this function when retrieving a date from database and echo in Italian format to screen:
function get_data_ita($date) {
if ($date == "")
return "";
$d = new DateTime($date);
return $d->format('d/m/Y');
}
where $date is mysql format like: 2017-12-31 14:00:00
Now, if I pass a correct format like: 2017-12-31 14:00:00 the function works.
But sometimes I need to use the SAME function, passing an already formatted date like: 30/12/2017. In this case, i get parsing error of course.
How can I check if date passed is already in Italian format, and if yes return the untouched date, if not, parse the date?
I need a function like:
function get_data_ita($date) {
if ( $date== ALREADY_IN_ITALIAN_FORMAT )
return $date;
if ($date == "")
return "";
$d = new DateTime($date);
return $d->format('d/m/Y');
}
echo get_data_ita("30/12/2017");
echo get_data_ita("2017-12-31 14:00:00");
ECHO:
30/12/2017
31/12/2017
UPDATE: I found solution myself:
function validateDate($date, $format = 'Y-m-d')
{
$d = DateTime::createFromFormat($format, $date);
return $d && $d->format($format) == $date;
}
function get_data_ita($datetime_db) {
if ( validateDate($datetime_db, 'd/m/Y') ) {
return $datetime_db;
}
if ($datetime_db == "")
return "";
$date = new DateTime($datetime_db);
return $date->format('d/m/Y');
}
Replace / to -
<?php
function get_data_ita($date) {
if ($date == ""){
return "";
}
$date = str_replace('/','-',$date);
$d = new DateTime($date);
return $d->format('d/m/Y');
}
echo get_data_ita("30/12/2017");
echo "\n";
echo get_data_ita("2017-12-31 14:00:00");
?>
Check demo : https://eval.in/918149
Strtotime returns false if the date is not a valid date format.
This works for your inputs but not if there are other date formats.
function get_data_ita($date) {
if ($date == "") return "";
If(strtotime($date) !== False){
$d = new DateTime($date);
}Else{
$d = DateTime::createFromFormat('d/m/Y', $date);
}
return $d->format('d/m/Y');
}
echo get_data_ita("30/12/2017");
echo get_data_ita("2017-12-31 14:00:00");
https://3v4l.org/kt5Vg

How can I check if a given date is newer than 3 days?

I have a date
2016-09-16
How can I check that if that date is less than 3 days old?
I'm being really stupid and the frustration is making me not figure it out
Here's my code
public function isNew()
{
return strtotime($this->created_at) > time() && strtotime($this->created_at) < strtotime('+3 days',time());
}
Should be easy to use DateTime and DateInterval to handle this.
$date = new DateTime('2016-09-16');
$diff = (new DateTime)->diff($date)->days;
return $diff < 3;
Using PHP's DateTime and DateInterval Classes would do you much good. Here's how:
<?php
function isNewerThan3Days($date) {
$today = new DateTime();
$date = new DateTime($date);
$diff = $today->diff($date);
$diffD = $diff->days;
if($diffD>=3){
return false;
}
return true;
}
var_dump(isNewerThan3Days("2016-09-14")); //<== YIELDS:: boolean true
Use diff(). It will return a DateInterval object. Within that object will be a days property (days) that you can access.
// compare two distinct dates:
$datetime1 = new DateTime('2016-09-16');
$datetime2 = new DateTime('2016-09-12');
$interval = $datetime1->diff($datetime2);
$daysOld = $interval->days;
// int(4)
// or compare today vs your date...
$datetime1 = new DateTime('2016-09-16');
$now = new DateTime();
$interval = $now->diff($datetime1);
$daysOld = $interval->days;
// int(0)
// then determine if it's at least 3 days old:
$is3daysOld = ($daysOld >= 3 ? true : false);
http://php.net/manual/en/datetime.diff.php
This should do it for you.
$date = new DateTime('2015-09-16');
$now = new DateTime();
$interval = $date->diff($now);
$difference = $interval->format('%a');
if($difference < 3) {
// $date is fewer than 3 days ago
}
In your isNew() method:
public function isNew() {
$created_at = new DateTime($this->created_at);
$now = new DateTime();
$interval = $created_at->diff($now);
$difference = $interval->format('%a');
if($difference < 3) {
return true;
}
return false;
}
return $this->created_at->diffInDays() < 3;
Without parameter diffInDays() will return the number of complete days between created_at and now.
Why don't you use Carbon ?
You can easily do that and many more in carbon like so :
$dt = Carbon::createFromDate(2011, 8, 1);
echo $dt->subDays(5)->diffForHumans(); // 5 days before

check upcomming birthday in a week 2 week or in a month using php

how to check is birthday is in this week,2week,or in month i have used below code to check but it return wrong calculation.
public function CountDown($birthdate, $days=7)
{
list($y,$d,$m) = explode('/',$birthdate);
$today = time();
$event = mktime(0,0,0,$m,$d,$y);
$apart = $event - $today;
if ($apart >= -86400)
{
$myevent = $event;
}
else
{
$myevent = mktime(09,0,0,$m,$d,$y);
}
$countdown = round(($myevent - $today)/86400);
if ($countdown <= $days)
{
return true;
}
return false;
}
Try this:
function CountDown($birthdate, $days=7)
{
# create today DateTime object
$td = new DateTime('today');
# create birth DateTime object, from format Y/d/m
$bd = DateTime::createFromFormat('!Y/d/m', $birthdate);
# set current year to birthdate
$bd->setDate($td->format('Y'), $bd->format('m'), $bd->format('d'));
# if birthdate is still in the past, set it to new year
if ($td > $bd) $bd->modify('+1 year');
# calculate difference in days
$countdown = $bd->diff($td)->days;
# return true if day difference is within your range
return $countdown <= $days;
}
demo
This worked for me
class Birthday{
public function CountDown($birthdate, $days=7)
{
list($y,$d,$m) = explode('/',$birthdate);
$today = time();
$event = mktime(0,0,0,$m,$d,$y);
$apart = $event - $today;
if ($apart >= -86400)
{
$myevent = $event;
}
else
{
$myevent = mktime(09,0,0,$m,$d);
}
$countdown = round(($myevent - $today)/86400);
if (($countdown <= $days))
{
return true;
}
return false;
}
}
$bday = new Birthday;
$count = $bday->CountDown("1969/16/11"); //today is 2014/14/11
var_dump($count); //returns true.
I just removed the year from the mktime() in $myevent. This changed the answers to be accurate.
The other way that it was being done made $countdown to be a huge negative number.

Compare date with date list in PHP

I have a date list like:
2012-04-11
2012-04-29
2012-04-26
2012-04-23
2012-03-21
2012-07-23
2012-12-19
I want to compare date list with today date. From that I want a list of dates which have already past. Also, I want a list of dates which are in the Future.
You can use strtotime() to convert your dates to UNIX timestamp then perform a simple greater/less than test. Do something like this:
<?php
$past_dates = array();
$future_dates = array();
$dates = array('2012-04-11', '2012-04-29', '2012-04-26', '2012-04-23', '2012-03-21', '2012-07-23', '2012-12-19');
$today = date('Y-m-d');
foreach($dates as $value) {
if(strtotime($value) < strtotime($today)) {
$past_dates[] = $value;
} else if(strtotime($value) > strtotime($today)) {
$future_dates[] = $value;
}
}
echo 'Past dates:';
echo '<pre>';
print_r($past_dates);
echo 'Future dates:';
echo '<pre>';
print_r($future_dates);
echo '</pre>';
echo 'Today is: ' . $today;
?>
Use PHP's strtotime() method:
$date = "2012-04-29";
$todays_date = date("Y-m-d");
$today = strtotime($todays_date);
$test_date = strtotime($date);
if ($test_date > $today) {
// Some Code
}
else {
// Some code
}
$dateArray = array('2012-04-11','2012-04-29','2012-04-26','2012-04-23','2012-03-21','2012-07-23','2012-12-19')
$pastDates = array();
$futureDates = array();
foreach ($dateArray as $date){
$dateTime = strtotime($date);
if (time() > $dateTime){
$pastDates[] = $date;
} else {
$futureDates[] = $date;
}
}
Try http://www.php.net/manual/en/datetime.diff.php
From manual:
Object oriented style
<?php
$datetime1 = new DateTime('2009-10-11');
$datetime2 = new DateTime('2009-10-13');
$interval = $datetime1->diff($datetime2);
echo $interval->format('%R%a days');
?>
Procedural style
<?php
$datetime1 = date_create('2009-10-11');
$datetime2 = date_create('2009-10-13');
$interval = date_diff($datetime1, $datetime2);
echo $interval->format('%R%a days');
?>
The above examples will output:
+2 days
Also maybe you will find usefull.
Example #2 DateTime object comparison
Note:
As of PHP 5.2.2, DateTime objects can be compared using comparison operators.
<?php
$date1 = new DateTime("now");
$date2 = new DateTime("tomorrow");
var_dump($date1 == $date2);
var_dump($date1 < $date2);
var_dump($date1 > $date2);
?>
The above example will output:
bool(false)
bool(true)
bool(false)

Undefined date_diff()

I'm trying to use date_diff():
$datetime1 = date_create('19.03.2010');
$datetime2 = date_create('22.04.2010');
$interval = date_diff($datetime1, $datetime2);
echo $interval->format('%R%d days');
Its doesn't work for me, gives an error:
Call to undefined function date_diff()
How can I get it work?
PHP 5.2 is used.
Thanks.
The function date_diff requires a PHP version of 5.3 or greater.
UPDATE
An example for PHP 5.2 (taken from the date_diff user comments).
<?php
function date_diff($date1, $date2) {
$current = $date1;
$datetime2 = date_create($date2);
$count = 0;
while(date_create($current) < $datetime2){
$current = gmdate("Y-m-d", strtotime("+1 day", strtotime($current)));
$count++;
}
return $count;
}
echo (date_diff('2010-3-9', '2011-4-10')." days <br \>");
?>
Here is a version that doesn't use Date objects, but these are of no use anyways in 5.2.
function date_diff($d1, $d2){
$d1 = (is_string($d1) ? strtotime($d1) : $d1);
$d2 = (is_string($d2) ? strtotime($d2) : $d2);
$diff_secs = abs($d1 - $d2);
return floor($diff_secs / (3600 * 24));
}
First convert both dates to mm/dd/yyyy format then do this :
$DateDiff = floor( strtotime($datetime2 ) - strtotime( $datetime1 ) ) / 86400 ;
//this will yield the resultant difference in days
function date_diff($date1, $date2) {
$count = 0;
//Ex 2012-10-01 and 2012-10-20
if(strtotime($date1) < strtotime($date2))
{
$current = $date1;
while(strtotime($current) < strtotime($date2)){
$current = date("Y-m-d",strtotime("+1 day", strtotime($current)));
$count++;
}
}
//Ex 2012-10-20 and 2012-10-01
else if(strtotime($date2) < strtotime($date1))
{
$current = $date2;
while(strtotime($current) < strtotime($date1)){
$current = date("Y-m-d",strtotime("+1 day", strtotime($current)));
$count++;
}
$current = $current * -1;
}
return $count; }
Converting your DateTime to Unix date type, and subtracting one from another:
The format->("U") is where the DateTime is converted.
$datetime1 = date_create('19.03.2010');
$datetime2 = date_create('22.04.2010');
$intervalInDays = ($datetime2->format("U") - $datetime1->format("U"))/(3600 * 24);
Not sure if this is Y2K38 safe but it's one of the simplest date_diff workarounds.

Categories