i've got users coming in from a different site and i'm getting that site to send across their timezone in a standard 'tz' format
Antarctica/Casey Antarctica/Davis
Antarctica/DumontDUrville Antarctica/Macquarie
Antarctica/Mawson Antarctica/McMurdo
How do i verify that this 'string' coming in is a VALID timezone entry?
this is what i'm doing
$script_tz = date_default_timezone_get();
if(!date_default_timezone_set($specifiedTimeZone))
{
date_default_timezone_set($script_tz);
$errormessage = "Invalid TimeZone";
return;
}
date_default_timezone_set($script_tz);
but i dont like it - seems kludgy.
testing it out:
Test1
$test1 = 'America/New_York';
$test2 = 'junk';
$start = microtime(true);
for($i=1;$i<10000;$i++)
{
if (in_array($test1, DateTimeZone::listIdentifiers())) {}else {}
if (in_array($test2, DateTimeZone::listIdentifiers())) {}else {}
}
$end = microtime(true);
echo $end-$start;
?>
9.7208099365234
Test2
<?php
$test1 = 'America/New_York';
$test2 = 'junk';
error_reporting(0);
$start = microtime(true);
for($i=1;$i<10000;$i++)
{
$script_tz = date_default_timezone_get();
if(!date_default_timezone_set($test1))
{
date_default_timezone_set($script_tz);
}
else
date_default_timezone_set($script_tz);
$script_tz = date_default_timezone_get();
if(!date_default_timezone_set($test2))
{
date_default_timezone_set($script_tz);
}
else
date_default_timezone_set($script_tz);
}
$end = microtime(true);
echo $end-$start;
?>
0.25762510299683
use DateTimeZone::listIdentifers()
if (in_array($timezone, DateTimeZone::listIdentifiers())) {
echo "valid";
}
else {
echo "invalid";
}
Validate against the tz database. There's http://code.google.com/p/tzdata/, that claims to provide the tz database in PHP format (whatever this means).
Check out this: How to check is timezone identifier valid from code?
Report different approaches to solve your problem.
There is a helper: timezone_identifiers_list() will return an array of strings of timezones. then you can use something like in_array to validate it.
if (in_array($timezone, timezone_identifiers_list())) {
// valid
}
You could take the list of supported timezones, save it in a file and compare what you're getting to the list:
http://php.net/manual/en/timezones.php
Related
I need to check if 2 different format date strings is a valid dates. The formats are: YYYY-MM-DD and YYYY.MM.DD. I found just only one date string format validation, like so:
function validateDate($date)
{
$d = DateTime::createFromFormat('Y-m-d', $date);
return $d && $d->format('Y-m-d') == $date;
}
function was copied from this answer or php.net
But how about two date formats validation? How to solve it? Thanks for any help
Try the following for both:
$date="2017-09-11";
if (preg_match("/^[0-9]{4}-(0[1-9]|1[0-2])-(0[1-9]|[1-2][0-9]|3[0-1])$/",$date)) {
echo true;
} else {
echo false;
}
$date="2017.10.22";
if (preg_match("/^[0-9]{4}.(0[1-9]|1[0-2]).(0[1-9]|[1-2][0-9]|3[0-1])$/",$date)) {
echo true;
} else {
echo false;
}
It uses regex to check if the format is valid or not.
OR
$date="2017-09-11";
$dt = DateTime::createFromFormat("Y-m-d", $date);
echo $dt !== false && !array_sum($dt->getLastErrors());
$date="2017.10.22";
$dt = DateTime::createFromFormat("Y.m.d", $date);
echo $dt !== false && !array_sum($dt->getLastErrors());
It uses DateTime to check the date against both formats.
Edit: While both are decent solutions, benchmarks show that in this case, preg_match is considerably faster than DateTime. https://3v4l.org/H8C73
Copy the original function, where you specify format as 2nd parameter, and then run function twice; as already mentioned in the comments.
function validateDate($date, $format = 'Y-m-d H:i:s')
{
$d = DateTime::createFromFormat($format, $date);
return $d && $d->format($format) == $date;
}
$isValid = validDate($date, 'Y-m-d') || validDate($date, 'Y.m.d');
function was copied from this answer or php.net
I want PHP to check if it's 8:30 AM and if it is, I want it to change a variable.
I tried,
$eightthirtyam = "08:30:00";
if(time() >= strtotime($eightthirtyam )){
$refresh = true;
}
But the boolean doesn't change. Any idea what I did wrong?
strtotime depends on the time zone.. so you should define timezone too.
You should set your default timezone before comparing.
http://php.net/strtotime
Example:
date_default_timezone_set('America/Los_Angeles');
$eightthirtyam = "08:30:00";
if(time() >= strtotime($eightthirtyam )){
$refresh = true;
}
http://codepad.org/GC0VA7nw
The function time() returns always timestamp that is timezone independent (=UTC), while strtotime() give a local time, So there is a timezone offset.
You need to subtract the timezone offset form the local time, before the compare, and check the live demo for a good understanding.
In php we have new DateTime function. So you can use this to match your date as give below example
$refresh = false;
$eightthirtyam = "08:30:00";
$date = new DateTime();
if($date->format('H:i:s') == $eightthirtyam)
{
$refresh = true;
}
Here is an example
$refresh = "false";
$eightthirtyam = "08:30:00";
$date = new DateTime("2017-06-07 8:30:00"); // suppose your system current time is this.
if($date->format('H:i:s') == $eightthirtyam)
{
$refresh = "true";
}
echo $refresh;
You can check answer by executing on online php editor http://www.writephponline.com/
Try above example, I think this may help you.
$hr= date('H:i');
if(strtotime($hr)==strtotime(08:30) ){
$refresh = true;
}
Please try this way. It will work i your case.
This will help you:
date_default_timezone_set('Asia/Kolkata');
$eightthirtyam = "08:30:00";
$refresh = false;
if(strtotime(date('H:i:s') == strtotime($eightthirtyam )){
$refresh = true;
}
Reference:-/ strtotime
the code is fine untill i know. but still if you want to do some actions, you can do something like this.
$refresh=false;
$eightthirtyam = "08:30:00";
if(time() >= strtotime($eightthirtyam ))
{
$refresh = true;
}
if($refresh)
{
//your statement is true do something here
}
else
{
//false statement
}
I am creating a web form for my work which is being validated using PHP. However, when I test the page I keep getting all of my error messages returned without the form being submitted properly when valid information is inputted. The following is a small section of the code (including the HTML sections).
<?php
$date =""
$dateerror = ""
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($_POST["date"])) {
$dateerror = "Date is required";
} else {
$date = test_input($_POST["date"]);
$array = explode("/", $date);
$day = $array[1];
$month = $array[0];
$year = $array[2];
if (!checkdate($month, $day, $year)) {
$dateerror = "Date mustbe in M/D/Y format";
} else {
date_default_timezone_set("America/Anchorage");
$today = strtotime("now");
if (strtotime($date)>=$today) {
$date = test_input($_POST["date"]);
} else {
$dateerror = "Date is before present day";
}
}
}
<input type="text" size="9" name="date" id="date" required title="Please enter current date"><?php echo $dateerror; ?><br>
Again, the PHP code just returns "Date is before present day" even when the date is the current date.
If you want to validate a date in PHP, the best way to do it is to use the DateTime class, and specifically the createFromFormat method.
This call will create a DateTime object set to the specified date in the given format, or false if it was an invalid date.
So for example:
<?php
$input = "05/08/2015";
$test = DateTime::createFromFormat('d/m/Y', $input);
if (!$test) {
print "You entered an invalid date";
die;
}
$now = new DateTime();
if ($test < $now) {
print "Date is before present.";
die;
}
?>
Simple as that. There's no need for regex, or for exploding the input, etc; just a single simple test. And you can also then use the $test variable to process the date as well once you've determined that it's valid, since it's a standard DateTime object.
[EDIT] I've added a bit in the code to deal with using the DateTime class to handle date comparisons, to give the 'before present' error.
The important point here is that if you have a DateTime object, you need to compare it with another DateTime object; the older strtotime() produces a different type of date resource to DateTime, and you can't use them together (at least not without converting between them all the time).
The solution: use date("M/D/Y"):
$today = strtotime(date("M/D/Y")); // 1432958400
$date = strtotime($_POST["date"]); // user input. 05-30-2015 will yield 1432958400
// the rest of your logic here
Here's the code specific solution:
<?php
$date =""
$dateerror = ""
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($_POST["date"])) {
$dateerror = "Date is required";
} else {
$date = test_input($_POST["date"]);
$array = explode("/", $date);
$day = $array[1];
$month = $array[0];
$year = $array[2];
if (!checkdate($month, $day, $year)) {
$dateerror = "Date mustbe in M/D/Y format";
} else {
date_default_timezone_set("America/Anchorage");
$today = strtotime(date("M/D/Y"));
if (strtotime($date)>=$today) {
$date = test_input($_POST["date"]);
} else {
$dateerror = "Date is before present day";
}
}
}
<input type="text" size="9" name="date" id="date" required title="Please enter current date"><?php echo $dateerror; ?><br>
I made this function and it works:
$myHour = "09:09";
$myHour = time_format($myHour);
function time_format($h){
$initial_string = $h;
$new = substr($h,1,strlen($h));
$h = substr($h,0,-4);
if ($h == "0"){
return $new;
}else{
return $initial_string;
}
}
This function verify it the string looks like: "01:02" and get rid of the first "0", so it will become "1:02" else if it looks like "13:13" it will return "13:13".
My question is how to improve my function? or if there exists other better method ? thx
use ltrim to just simply remove the leading 0 if there is one. I assume there is a reason you cant just change the date format which generates the string ?
function time_format($h){
return ltrim($h, "0");
}
But changing the date format is the best option
this will be your shortened function, still readable
function time_format($h){
if (substr($h, 0, 1) == "0"){
return substr($h, 1);
}else{
return $h;
}
}
this would be even shorter
function time_format($h){
return substr($h, 0, 1) == "0" ? substr($h, 1) : $h;
}
this one is even without the if operators
to read more about it, here is a link.
<?php
$date = new DateTime('2000-01-01');
echo $date->format('Y-m-d H:i:s');
?>
Please have a detailed look here:
http://www.php.net/manual/en/datetime.format.php
You can get a DateTime object by UnixTimestamp (if needed) with this way
$dtStr = date("c", $timeStamp);
$date = new DateTime($dtStr);
Source: Creating DateTime from timestamp in PHP < 5.3
use PHP date function
try to google first..
So I'd like to add the current time to the database, to a specific user when he does something, and later on read it, and check if that time has passed (by checking current time and substracting that from the one in database; to check if it has passed or not)
So how would I do this? I tried with something like this:
$date = date("YmWjis");
$calculate = $date - $info['lastvisit'];
if($calculate <= -1)
{
echo "you need to wait before visiting again"; // (just an example)
} else {
//do something
}
I also tried both:
!$calculate < 0
$calculate < 0
etc. But I can't get it to work. Can anyone help me? :P
edit for Parag;
$date = date("YmWjis");
$dote = date("YmWjis") + $time; // ($time is set earlier and is 30 seconds)
echo "wait " . $date = $date - $dote . " seconds until next visit";
work?
It says like "wait 20138269786674 seconds until next visit".
You can try something like this:
$dateDiff = new DateTime("2014-04-27 22:00:15");
$date = new DateTime();
$diff = $date->diff($dateDiff);
if($diff->invert == 0)
{
echo "you need to wait before visiting again"; // (just an example)
} else {
//do something
}
$db_time = "2014/04/28 15:15:15";
$cur_time = "2014/04/28 18:15:15";
if(strtotime($cur_time) > strtotime($db_time))
{
// Current time exceeds DB time
$diff = date('Y/m/d H:i:s', strtotime($cur_time)-strtotime($db_time));
echo $diff;
}
else
{
// Current time didn't exceeds DB time
}
UPDATE
$date = strtotime(date("YmWjis"));
$dote = strtotime(date("YmWjis")) + $time; // ($time is set earlier and is 30 seconds)
echo "wait " . $date = $date - $dote . " seconds until next visit";
DEMO
http://3v4l.org/LBIXu
Don't use a database. This does the job without the db overhead. It uses PHP sessions.
<?php
session_start();
if (!isset($_SESSION['lastVisitTime'])) {
$_SESSION['lastVisitTime']=new DateTime();
} else {
$now=new DateTime();
if ($_SESSION['lastVisitTime']->diff($now) > $someMaxValueYouDefine) {
echo "You must wait before visiting again.";
}
}