how to resolve time data comparism in php - php

I have a contract time format like this one July 28, 2020 14:18:25 that I want check if it has expired from now. But am not getting is correct. it seems to be some minutes difference
here is the code
//$now = strtotime(date("m-d-y H:i:s"));
$now = time();
$contractDate = strtotime("July 28, 2020 14:18:25");
// check if contract is still on or has ended from now
if($now < $contractDate) {
echo "contract is on";
} else {
echo "contract time ended!";
}

Could it be the timezone problem (that your time() is off by some).
You solve it by setting the timezone explicitly in your PHP scripts. You can do this with date_default_timezone_set():
date_default_timezone_set('America/Los_Angeles');
Here is the list of PHP supported timezones.
You may also want to try a test script calling date_default_timezone_get() to see what it's actually set to to verify that this is in fact the problem.
You can also try with DateTime class
$d1 = new DateTime();
$d2 = new DateTime("July 28, 2020 14:18:25");
$diff = $d1->diff($d2);
echo $diff->format('%H:%I:%S');

You are not able to get it right because of your format. It should work if you can get your dates to be in the "yyyy-mm-dd" format. Try this:
$now = strtotime(date("y-m-d"));
$now = time();
$contractDate = strtotime("2020-07-28");
if($now < $contractDate) {
echo "contract is on";
} else {
echo "contract time ended!";
}

Related

loop to go between two dates and output dates in unix format? [duplicate]

How do I get timestamp from e.g. 22-09-2008?
This method works on both Windows and Unix and is time-zone aware, which is probably what you want if you work with dates.
If you don't care about timezone, or want to use the time zone your server uses:
$d = DateTime::createFromFormat('d-m-Y H:i:s', '22-09-2008 00:00:00');
if ($d === false) {
die("Incorrect date string");
} else {
echo $d->getTimestamp();
}
1222093324 (This will differ depending on your server time zone...)
If you want to specify in which time zone, here EST. (Same as New York.)
$d = DateTime::createFromFormat(
'd-m-Y H:i:s',
'22-09-2008 00:00:00',
new DateTimeZone('EST')
);
if ($d === false) {
die("Incorrect date string");
} else {
echo $d->getTimestamp();
}
1222093305
Or if you want to use UTC. (Same as "GMT".)
$d = DateTime::createFromFormat(
'd-m-Y H:i:s',
'22-09-2008 00:00:00',
new DateTimeZone('UTC')
);
if ($d === false) {
die("Incorrect date string");
} else {
echo $d->getTimestamp();
}
1222093289
Regardless, it's always a good starting point to be strict when parsing strings into structured data. It can save awkward debugging in the future. Therefore I recommend to always specify date format.
There is also strptime() which expects exactly one format:
$a = strptime('22-09-2008', '%d-%m-%Y');
$timestamp = mktime(0, 0, 0, $a['tm_mon']+1, $a['tm_mday'], $a['tm_year']+1900);
Warnings:
This function is not implemented on Windows
This function has been DEPRECATED as of PHP 8.1.0. Relying on this function is highly discouraged.
With DateTime API:
$dateTime = new DateTime('2008-09-22');
echo $dateTime->format('U');
// or
$date = new DateTime('2008-09-22');
echo $date->getTimestamp();
The same with the procedural API:
$date = date_create('2008-09-22');
echo date_format($date, 'U');
// or
$date = date_create('2008-09-22');
echo date_timestamp_get($date);
If the above fails because you are using a unsupported format, you can use
$date = DateTime::createFromFormat('!d-m-Y', '22-09-2008');
echo $dateTime->format('U');
// or
$date = date_parse_from_format('!d-m-Y', '22-09-2008');
echo date_format($date, 'U');
Note that if you do not set the !, the time portion will be set to current time, which is different from the first four which will use midnight when you omit the time.
Yet another alternative is to use the IntlDateFormatter API:
$formatter = new IntlDateFormatter(
'en_US',
IntlDateFormatter::FULL,
IntlDateFormatter::FULL,
'GMT',
IntlDateFormatter::GREGORIAN,
'dd-MM-yyyy'
);
echo $formatter->parse('22-09-2008');
Unless you are working with localized date strings, the easier choice is likely DateTime.
Be careful with functions like strtotime() that try to "guess" what you mean (it doesn't guess of course, the rules are here).
Indeed 22-09-2008 will be parsed as 22 September 2008, as it is the only reasonable thing.
How will 08-09-2008 be parsed? Probably 09 August 2008.
What about 2008-09-50? Some versions of PHP parse this as 20 October 2008.
So, if you are sure your input is in DD-MM-YYYY format, it's better to use the solution offered by #Armin Ronacher.
This method works on both Windows and Unix and is time-zone aware, which is probably what you want if you work with dates.
If you don't care about timezone, or want to use the time zone your server uses:
$d = DateTime::createFromFormat('d-m-Y H:i:s', '22-09-2008 00:00:00');
if ($d === false) {
die("Incorrect date string");
} else {
echo $d->getTimestamp();
}
1222093324 (This will differ depending on your server time zone...)
If you want to specify in which time zone, here EST. (Same as New York.)
$d = DateTime::createFromFormat(
'd-m-Y H:i:s',
'22-09-2008 00:00:00',
new DateTimeZone('EST')
);
if ($d === false) {
die("Incorrect date string");
} else {
echo $d->getTimestamp();
}
1222093305
Or if you want to use UTC. (Same as "GMT".)
$d = DateTime::createFromFormat(
'd-m-Y H:i:s',
'22-09-2008 00:00:00',
new DateTimeZone('UTC')
);
if ($d === false) {
die("Incorrect date string");
} else {
echo $d->getTimestamp();
}
1222093289
Regardless, it's always a good starting point to be strict when parsing strings into structured data. It can save awkward debugging in the future. Therefore I recommend to always specify date format.
Using mktime:
list($day, $month, $year) = explode('-', '22-09-2008');
echo mktime(0, 0, 0, $month, $day, $year);
Using strtotime() function you can easily convert date to timestamp
<?php
// set default timezone
date_default_timezone_set('America/Los_Angeles');
//define date and time
$date = date("d M Y H:i:s");
// output
echo strtotime($date);
?>
More info: http://php.net/manual/en/function.strtotime.php
Online conversion tool: http://freeonlinetools24.com/
Here is a very simple and effective solution using the split and mtime functions:
$date="30/07/2010 13:24"; //Date example
list($day, $month, $year, $hour, $minute) = split('[/ :]', $date);
//The variables should be arranged according to your date format and so the separators
$timestamp = mktime($hour, $minute, 0, $month, $day, $year);
echo date("r", $timestamp);
It worked like a charm for me.
Use PHP function strtotime()
echo strtotime('2019/06/06');
date — Format a local time/date
Given that the function strptime() does not work for Windows and strtotime() can return unexpected results, I recommend using date_parse_from_format():
$date = date_parse_from_format('d-m-Y', '22-09-2008');
$timestamp = mktime(0, 0, 0, $date['month'], $date['day'], $date['year']);
If you know the format use strptime because strtotime does a guess for the format, which might not always be correct. Since strptime is not implemented in Windows there is a custom function
http://nl3.php.net/manual/en/function.strptime.php#86572
Remember that the returnvalue tm_year is from 1900! and tm_month is 0-11
Example:
$a = strptime('22-09-2008', '%d-%m-%Y');
$timestamp = mktime(0, 0, 0, $a['tm_mon']+1, $a['tm_mday'], $a['tm_year']+1900)
If you want to know for sure whether a date gets parsed into something you expect, you can use DateTime::createFromFormat():
$d = DateTime::createFromFormat('d-m-Y', '22-09-2008');
if ($d === false) {
die("Woah, that date doesn't look right!");
}
echo $d->format('Y-m-d'), PHP_EOL;
// prints 2008-09-22
It's obvious in this case, but e.g. 03-04-2008 could be 3rd of April or 4th of March depending on where you come from :)
<?php echo date('M j Y g:i A', strtotime('2013-11-15 13:01:02')); ?>
http://php.net/manual/en/function.date.php
$time = '22-09-2008';
echo strtotime($time);
function date_to_stamp( $date, $slash_time = true, $timezone = 'Europe/London', $expression = "#^\d{2}([^\d]*)\d{2}([^\d]*)\d{4}$#is" ) {
$return = false;
$_timezone = date_default_timezone_get();
date_default_timezone_set( $timezone );
if( preg_match( $expression, $date, $matches ) )
$return = date( "Y-m-d " . ( $slash_time ? '00:00:00' : "h:i:s" ), strtotime( str_replace( array($matches[1], $matches[2]), '-', $date ) . ' ' . date("h:i:s") ) );
date_default_timezone_set( $_timezone );
return $return;
}
// expression may need changing in relation to timezone
echo date_to_stamp('19/03/1986', false) . '<br />';
echo date_to_stamp('19**03**1986', false) . '<br />';
echo date_to_stamp('19.03.1986') . '<br />';
echo date_to_stamp('19.03.1986', false, 'Asia/Aden') . '<br />';
echo date('Y-m-d h:i:s') . '<br />';
//1986-03-19 02:37:30
//1986-03-19 02:37:30
//1986-03-19 00:00:00
//1986-03-19 05:37:30
//2012-02-12 02:37:30
<?php echo date('U') ?>
If you want, put it in a MySQL input type timestamp. The above works very well (only in PHP 5 or later):
<?php $timestamp_for_mysql = date('c') ?>
Here is how I'd do it:
function dateToTimestamp($date, $format, $timezone='Europe/Belgrade')
{
//returns an array containing day start and day end timestamps
$old_timezone=date_timezone_get();
date_default_timezone_set($timezone);
$date=strptime($date,$format);
$day_start=mktime(0,0,0,++$date['tm_mon'],++$date['tm_mday'],($date['tm_year']+1900));
$day_end=$day_start+(60*60*24);
date_default_timezone_set($old_timezone);
return array('day_start'=>$day_start, 'day_end'=>$day_end);
}
$timestamps=dateToTimestamp('15.02.1991.', '%d.%m.%Y.', 'Europe/London');
$day_start=$timestamps['day_start'];
This way, you let the function know what date format you are using and even specify the timezone.
If you already have the date in that format, you only need to call the "strtotime" function in PHP.
$date = '22-09-2008';
$timestamp = strtotime($date);
echo $timestamp; // 1222041600
Or in a single line:
echo strtotime('22-09-2008');
Short and simple.
For PHP >=5.3, 7 & 8 the this may work-
$date = date_parse_from_format('%Y-%m-%d', "2022-11-15"); //here you can give your desired date in desired format.
//just need to keep in mind that date and format matches.
$timestamp = mktime(0, 0, 0, $date['month'], $date['day'], $date['year'] + 2000); //this will return the timestamp
$finalDate= date('Y-m-d H:i:s', $timestamp); //now you can convert your timestamp to desired dateTime format.
Docs:
date_parse_from_format()
mktime()
date()
Please be careful about time/zone if you set it to save dates in database, as I got an issue when I compared dates from mysql that converted to timestamp using strtotime. you must use exactly same time/zone before converting date to timestamp otherwise, strtotime() will use default server timezone.
Please see this example: https://3v4l.org/BRlmV
function getthistime($type, $modify = null) {
$now = new DateTime(null, new DateTimeZone('Asia/Baghdad'));
if($modify) {
$now->modify($modify);
}
if(!isset($type) || $type == 'datetime') {
return $now->format('Y-m-d H:i:s');
}
if($type == 'time') {
return $now->format('H:i:s');
}
if($type == 'timestamp') {
return $now->getTimestamp();
}
}
function timestampfromdate($date) {
return DateTime::createFromFormat('Y-m-d H:i:s', $date, new DateTimeZone('Asia/Baghdad'))->getTimestamp();
}
echo getthistime('timestamp')."--".
timestampfromdate(getthistime('datetime'))."--".
strtotime(getthistime('datetime'));
//getthistime('timestamp') == timestampfromdate(getthistime('datetime')) (true)
//getthistime('timestamp') == strtotime(getthistime('datetime')) (false)
I have used this format:
$presentDateTime = strtotime(date('Y-m-d H:i:s'));
If you're looking to convert a UTC datetime (2016-02-14T12:24:48.321Z) to timestamp, here's how you'd do it:
function UTCToTimestamp($utc_datetime_str)
{
preg_match_all('/(.+?)T(.+?)\.(.*?)Z/i', $utc_datetime_str, $matches_arr);
$datetime_str = $matches_arr[1][0]." ".$matches_arr[2][0];
return strtotime($datetime_str);
}
$my_utc_datetime_str = '2016-02-14T12:24:48.321Z';
$my_timestamp_str = UTCToTimestamp($my_utc_datetime_str);

PHP date function giving a random number

Hello i'm making a php script to send an email on a client's birthday, basicly i'm looping through every client's birthdates and checking with today's date and if they match, an email is sent. Although the date function is giving a random number instead of today's date, the number is: 1505451600.
Maybe i'm doing something wrong in the code? Does anyone know a way to fix this?
$get_birthday = $DB_con->prepare("SELECT email, dt_nascimento FROM clientes");
if ($get_birthday->execute()) {
while ($array_birthday = $get_birthday->fetch(PDO::FETCH_ASSOC)) {
$birthdate = date('m d', strtotime($array_birthday['dt_nascimento']));
// echo "</br> data:".$array_birthday['dt_nascimento'];
// echo "</br>".$birthdate;
$now = date("m/d");
$now = strtotime($now);
// echo "</br>now: ".$now;
$email = $array_birthday['email'];
if ($now == $birthdate) {
include"PHPMailer/email_birthday.php";
}
}
}
There are 2 changes you need to make for your code to work:
(1) Remove this line:
$now = strtotime($now);
Reason: You don't want a timestamp. You want a formatted date.
(2) Change "m d" on this line:
$birthdate = date('m d', strtotime($array_birthday['dt_nascimento']));
to "m/d" like so:
$birthdate = date('m/d', strtotime($array_birthday['dt_nascimento']));
Reason: you need to format $birthdate and $now the same way to make the comparison work.
I remove the $now conversion to timestamp and change the $birthdate format to the same as $now.
This is the working code :
$get_birthday = $DB_con->prepare("SELECT email, dt_nascimento FROM clientes");
if ($get_birthday->execute()) {
while ($array_birthday = $get_birthday->fetch(PDO::FETCH_ASSOC)) {
$birthdate = date('m d', strtotime($array_birthday['dt_nascimento']));
// echo "</br> data:".$array_birthday['dt_nascimento'];
// echo "</br>".$birthdate;
$now = date("m d");
// echo "</br>now: ".$now;
$email = $array_birthday['email'];
if ($now == $birthdate) {
include"PHPMailer/email_birthday.php";
}
}
}
The reason it gives you a number is how computers measure time is the number of seconds since 1/1/1970 00:00 (UTC (Universal Time)).
1505451600 Is equivalent to: 09/15/2017 # 5:00am (UTC)
this happens because:
date("m/d") returns 9/15 (today month/day)
then strtotime tries to convert this string into unix timestamp, as soon as year is not in string, current year (2017) is assumed
as soon as time part is not there, midnight in your timezone is assumed (5am utc)
this is why final time is 1505451600

PHP get time from personal identity number under 1970

I have problem, I can't get time from personal identity number under 1970, I need to solve that, but using time. My function looks like. I don't know which way I can go. Thanks!
function getBirthDayFromRd($rd){
$day = substr($rd,4,2);
$month = substr($rd, 2,2);
$year = substr($rd, 0,2);
if($month>=51 and $month<=62){
$month = $month - 50;
}
$time = strtotime($day.".".$month.".".$year);
return date("d.m.Y", $time);
}
strtotime() fails due to its being tied to the Unix epoch which does not support dates prior to 1970. Just use DateTime which can handle pre-1970 dates and convert dates easily:
function getBirthDayFromRd($rd){
$date = DateTime::createFromFormat('ymd',$rd);
if($date->format('Y') > date("Y")) {
$date->modify('-100 years');
}
return $date->format('d.m.Y');
}
DateTime::createFromFormat() parses your date and creates the DateTime object. Then we just call DateTime::format() to format it in the desired format.
update
Just fixed a bug where pre-1970 dates were shown 100 years in the future.
Demo
I solve it another way, but u started me up.
if($year < 70){
$year = $year+1900;
$time = date_create_from_format("d.m.Y", $day.".".$month.".".$year);
return date_format($time, "d.m.Y");
}else{
$time = strtotime($day.".".$month.".".$year);
return date("d.m.Y", $time);
}

PHP date compare older than 15 days

i am struggling for a long time to set a specific date but i am not getting correct out put.
i want to get date from user and compare that date with the date 15 days older then today. if it is older than 15 days then convert to today else print what it is.
$todaydate= $_GET['date'];// getting date as 201013 ddmmyy submitted by user
$todaydate=preg_replace("/[^0-9,.]/", "", $todaydate);
$today =date("dmy"); //today ddmmyy
$older= date("dmy",strtotime("-15 day")); // before 15 days 051013
if ($todaydate <= $older){
$todaydate= $today;}
problem is, it is taking date as number and giving wrong result.
Comparing date strings is a bit hacky and prone to failure. Try comparing actual date objects
$userDate = DateTime::createFromFormat('dmy', $_GET['date']);
if ($userDate === false) {
throw new InvalidArgumentException('Invalid date string');
}
$cmp = new DateTime('15 days ago');
if ($userDate <= $cmp) {
$userDate = new DateTime();
}
Also, strtotime has some severe limitations (see http://php.net/manual/function.strtotime.php#refsect1-function.strtotime-notesand) and is not useful in non-US locales. The DateTime class is much more flexible and up-to-date.
try this one:
<?php
$todaydate = date(d-m-Y,strtotime($_GET['date']));
$today = date("d-m-Y");
$older= date("d-m-Y",strtotime("-15 day"));
if (strtotime($todaydate) <= strtotime($older))
{
$todaydate= $today;
}
?>
$previousDate = "2012-09-30";
if (strtotime($previousDate) <= strtotime("-15 days")) {
//the date in $previousDate is earlier or is equal to the date 15 days before from today
}

How do you change the timezone in PHP for an existing timestamp?

The code for the date and time function:
function date_and_time($format,$timestamp) {
$date_and_time = date($format,$timestamp);
return $date_and_time;
}
And then the code to display it:
<?php
echo date_and_time("dS F Y", strtotime($profile[last_activity_date_and_time]));
?>
The value of $profile[last_activity_date_and_time] is 2010-01-18 14:34:04
When displayed it shows up as 18th January 2010 - 02:34pm
But, is there any way to change the timezone it is displayed in?
Not sure if this what you're looking for, but try DateTime
date_default_timezone_set('Europe/London');
$datetime = new DateTime();
$datetime->setTimestamp($yourTimestamp);
echo $datetime->getTimezone()->getName();
echo $datetime->format(DATE_ATOM);
$la_time = new DateTimeZone('America/Los_Angeles');
$datetime->setTimezone($la_time);
echo $datetime->getTimezone()->getName();
echo $datetime->format(DATE_ATOM);
You can use the this function to set default time zone:
date_default_timezone_set('Europe/London');

Categories