Php, how to determine if a string is a time? - php

I want to detect if a string is a time (00:18:31). I know about strtotime() but it also detects "now" as OK, and so on. I need a real solution.

Try this:-
if (DateTime::createFromFormat('H:i:s', $yourtimeString) !== FALSE) {
echo "it's a date";
}else{
echo "it's not a date";
}
Input:- 00:18:31 Output:- it's a date
Input:- now,NOW,now(),NOW() Output:- it's not a date

The validateTime() function checks whether the given string is a valid time. using DateTime class and createFromFormat() static method.
function validateTime($time, $format = 'H:i:s'){
$t = DateTime::createFromFormat($format, $time);
return $t && $t->format($format) === $time;
}
// Returns true
echo var_dump(validateTime("00:18:31"));
echo var_dump(validateTime("23:59:59"));
echo var_dump(validateTime("00:02:30"));
// Returns false
echo var_dump(validateTime("31:18:31"));
echo var_dump(validateTime("24:00:00"));
echo var_dump(validateTime("23:60:60"));
Explanation of $t->format($format) === $time
is a test to check if the time is indeed a real time or not. for instance 23:59:59 is valid time but 24:00:00 is not.
We all know that 23:59:59 is the max acceptable Human time. and 24:00:00 is not. However, We can pretend it means the next day at 00:00:00. that is what DateTime::createFromFormat do! when we give it a time exceed the maximum. It accept it by adding the remaining time to the next day.
For example
today is 2021-05-14 23:59:59
and time to check if we give it to createFromFormat is 24:02:30 the date becomes next day 2021-05-15 00:02:30
We notice that 24:02:30 != 00:02:30. So from that we can summarize that is not valid time. To be valid it must be the same!

Related

Check if a timezone has passed a certain time

I am having a bit of trouble working out how to validate whether a timezone has passed a certain time (local to the time zone).
So for instance, if the time in London has passed 18:00:00
$tz = new DateTimeZone('Europe/London');
$datetime1->setTimezone($tz); // calculates with new TZ now
if ($datetime1->format('H:i:s') >= strtotime('18:00:00')) {
echo "time has passed";
} else {
echo "time has NOT passed";
}
The problem with this is that strtotime('18:00:00') seems to be using the server time.
If I echo strtotime('18:00:00'); will return 1470247200 which is the amount of seconds since 1970 but this will not be the 6pm time for another timezone for instance America/New_York which at the time of writing this has not passed.
Any idea how this can be done?
Thanks,
Use DateTime's own comparison feature since it includes time zone support:
$tz = new DateTimeZone('Europe/London');
$datetime1->setTimezone($tz); // calculates with new TZ now
$datetime2 = new \DateTime('18:00:00', $tz);
if ($datetime1 >= sdatetime2) {
echo "time has passed";
} else {
echo "time has NOT passed";
}
I think this should work:
if ($datetime1->format('H:i:s') >= '18:00:00') {
The left side is a string, and every component contains leading zeros, so you can just do a string comparison with the right side.
(This assumes that you consider midnight of the next day to not have "passed" 18:00:00.)

Get the date from a time string

Is there a way to convert an input time string (ex: 01:13) to a Zend date object, so that I store it later in a timestamp column in a Mysql database.
Examples:
If the current datetime is 2013-07-15 17:33:07 and the user inputs 18:05 the output should be 2013-07-15 18:05:00.
If the current datetime is 2013-07-15 17:33:07 and the user inputs 02:09 the output should be 2013-07-16 02:09:00. Notice that since the time entered was lower than the current time, so it was treated as tomorrows time.
I simply want to get the next point in time that satisfies the entered time. I'm open for solution using plain PHP or Zend_Date.
I think you should compare the current time with the time entered by the user and create a DateTime object of either "today" or "tomorrow". DateTime accepts strtotime() relative time parameters.
Quick hack. Works as of today, 15.07.2013 23:58 local time:
$nextTime = new DateTime('today 18:10');
if ($nextTime < new DateTime('now')) { // DateTime comparison works since 5.2.2
$nextTime = new DateTime('tomorrow 18:10');
}
echo $nextTime->format('d.m.Y H:i:s');
here is working example for you just add your dynamic variable to check date with user inputs
You can use mktime function to manage your date.
$input_date = date("Y-m-d H:i:s",mktime(18,05,0,date("m"),date("d"),date("Y")));
echo "current time".$current_time = date('Y-m-d H:m:s');
echo "<br>User input is ".$input_date;
if(strtotime($current_time) > strtotime($input_date)){
$input_date = date("Y-m-d H:i:s",mktime(18,05,0,date("m"),date("d")+1,date("Y")));
echo "in";
}else{
// nothing to do
}
echo "<br> result->".$input_date;
i hope it will sure solve your issue

Compare times in PHP as string

I need a method that gets two strings that represents a DateTime (in the MySql syntax) and returns the time difference between them.
Then I need to compare that time to 3 seconds so I could block a Brute Force attack on my server.
I've messed a lot with Google and I managed to get the string representation of the DateTime object, but I can't manage to convert and compare them.
$time_str1 = '2011-09-10 19:59:23'; // first string datetime from DB
$time_str2 = '2011-09-10 19:59:24'; // second string datetime from DB
// first DateTime object created based on the MySQL datetime format
$dt1 = DateTime::createFromFormat('Y-m-d H:i:s', $time_str1);
// second DateTime object created based on the MySQL datetime format
$dt2 = DateTime::createFromFormat('Y-m-d H:i:s', $time_str2);
// difference comparison to check if at least 3 seconds have passed
if ( ($dt2->format('U') - $dt1->format('U')) > 3) {
echo 'Ok, no brute force'; // yes, three seconds have passed
} else{
echo 'We got you newbie'; // nope, three second haven't passed
}
$diffInSeconds = $dateTimeLater->format('U') - $dateTimeFirst->format('U');
strtotime( $timeStr ) which will convert to the amount of seconds since epoch http://en.wikipedia.org/wiki/Unix_epoch . Then you can just use standard mathematical operators. Be warned, strtotime can be inaccurate sometimes. To convert back, date("m-d-Y H:i:s", $time)
Heres an alternative method using a session, no need to query a db for a timestamp:
<?php
session_start();
function post_check($limit){
//Check for first time
if(isset($_SESSION['post_check'])){
//Check for count on failed
if(isset($_SESSION['post_check_count'])){
//If fail count is more then 3 block till user closes down browser
if($_SESSION['post_check_count']>$limit){
die('Too many requsets to the server, please close down your browesr and try again.');
}
}else{
//Set for count on failed
$_SESSION['post_check_count']=0;
}
//Check (time-limit) against timestamp held in session
if(($_SESSION['post_check']+$limit)<=time()){
//Update timestamp
$_SESSION['post_check']=time();
//Ok
return true;
}else{
//Update Fail count
$_SESSION['post_check_count']++;
//Fail
return false;
}
}else{
//Set for first time
$_SESSION['post_check']=time();
return true;
}
}
//Pretty self explanitry here
if(post_check('3')===true){
echo 'Allowed: handle post stuff here';
}else{
echo'Too many requests within given time limit do nothing';
}
?>
On the MySQL side:
SELECT UNIX_TIMESTAMP(my_time) FROM my_table
On the PHP side, you then have UNIX timestamps in seconds, which you can compare.

PHP Compare datetime values

In my PHP application I'm trying to compare date time values like the following:
if($datetime_from_db < date('Y-m-d H:i:s'))
{
// then do something
}
Both values are in the same format. What I can't figure out is why it only compares the date and ignores the time. Both the date and the time values are important for me but I don't know how to make it work.
Comparing a string like "2011-02-14 15:46:00" to another string doesn't actually compare dates, it compares two strings according string parsing numeric rules. You will need to compare actual numeric timestamps:
strtotime($datetime_from_db) < time()
If you want this to work with dates past 2038, you can't use strtotime() or time().
See this question for the explanation.
A better approach:
new DateTime($datetime_from_db) < new DateTime();
This may help you.
$today = date("m-d-Y H:i:s");
$thisMonth =date("m");
$thisYear = date("y");
$expectedDate = $thisMonth."-08-$thisYear 23:58:00";
//pr($today);
//pr($expectedDate);
if (strtotime($expectedDate) > strtotime($today)) {
echo "Expected date is greater then current date";
return ;
} else
{
echo "Expected date is lesser then current date";
}
Here is a solution where we use strtotime. I give two examples.
First one comparing the whole timestamp. Second one is just compare the date.
<?php
$date = "2022-10-06 17:49:10"; // string. can set any current timestamp
#example 1 - compare the date and time Y-m-d H:i:s
if(date("Y-m-d H:i:s" , strtotime($date)) >= date("Y-m-d H:i:s")){
echo "the date checked is bigger than today";
}else{
echo "the date checked is smaller than today";
}
#example 2 - compare the date only Y-m-d
if(date("Y-m-d" , strtotime($date)) == date("Y-m-d")){
echo "same day is true";
}else{
echo "same day is false";
}

PHP - why is this date function not erroring out

function convertDT($TS) {
$TS = strtotime($TS);
$TS -= date("Z");
$newTS = date("Y-m-d\TH:i:s\Z", $TS);
return $newTS;
}
echo "Good: ".convertDT('2010-04-20 01:23:45')."\n";
echo "Bad: ".convertDT('2010-31-20 01:23:45')."\n";
The second date returns: 1969-12-31T23:00:00Z
Why? Should this error?
strtotime() returns false when you give it an invalid timestamp. false is equivalent to 0 if you use it in an integer context, so when you pass it to this line:
$newTS = date("Y-m-d\TH:i:s\Z", $TS);
You are effectively creating a date from a timestamp of 0. In terms of the UNIX epoch, 0 is January 1st, 1970, which is where you're getting your end result from.
Your best bet would be soemthing like this:
$TS = strtotime($TS);
if($TS === false) {
throw new Exception("Invalid timestamp.");
}
//etc.
On your second date, you are trying to create a date of month 31 and of day 20. Even if you reversed these, it wouldn't make sense. Probably a typo.
read this http://php.net/manual/en/function.strtotime.php
Errors/Exceptions
Every call to a date/time function
will generate a E_NOTICE if the time
zone is not valid, and/or a E_STRICT
or E_WARNING message if using the
system settings or the TZ environment
variable. See also
date_default_timezone_set()
This function will not generate any error even if input string is not valid.

Categories