Fix time string - php

This should be very easy, but I am not getting it. I wish to receive hours:minutes, and return hours:minutes:seconds in 00:00:00 format. The following falls way short. Recommendations on the best way to do this? Thank you
<?php
function fixTime($t)
{
$a = explode(':', trim($t));
return ((count($a)==2) && ($h=$a[0]) && ($m=$a[1]) && ($h>=0) && ($m>=0) && ($h<=23) && ($m<=59))?$h.':'.$m.':00':'00:00:00';
}
echo(fixTime('23:33').'<br />');
echo(fixTime('05:00').'<br />');
echo(fixTime('5:00').'<br />');
?>

The strtotime function will help you out here:
function fixTime($t) {
return date('H:i:s', strtotime($t));
}
echo fixTime('23:33'); // 23:33:00
echo fixTime('05:00'); // 05:00:00
echo fixTime('5:00'); // 05:00:00
Also, see the date function for a list of formatting options available.
To validate such simple input, a regular expression might be helpful:
function fixTime($t) {
if (!preg_match('/^([01][0-9]|2[0-3]|[0-9]):[0-5][0-9]$/', $t)) {
return false;
}
return date('H:i:s', strtotime($t));
}
echo fixTime('23:33'); // 23:33:00
echo fixTime('33:33'); // false
if (fixTime('33:33') === false) {
// invalid date supplied
}

Related

PHP date format - date if date or nothing if null

I have this function to format a date from the database into a human-friendly format, but the date is an optional field and can be null. Is there an elegant way for date be formatted if it exists or be ' ' if it is null?
public function start_date_formatted()
{
return date("M j, 'y", strtotime($this->start_date));
}
I think this will work
public function start_date_formatted()
{
if ($this->start_date)) {
return date("M j, 'y", strtotime($this->start_date));
} else {
return 0; // or whatever you want to return
}
}
Here is a helper to validate date:
function validateDate($date, $format = 'Y-m-d')
{
$d = DateTime::createFromFormat($format, $date);
return $d && $d->format($format) == $date;
}
Hope this will help you!!
Try this code:
public function start_date_formatted()
{
if( !is_null($this->start_date) ) {
return date("M j, 'y", strtotime($this->start_date));
}
return '';
}
You can uset isset, it will check if the date is set or not
public function start_date_formatted()
{
if ( isset($this->start_date) && !( is_null($this->start_date) ) ) { // Check if the properties is set and not null (maybe is_null is overkill)
return date("M j, 'y", strtotime($this->start_date));
} else {
return '';
}
}

Validation Error dates PHP

I'm trying to validate dates in PHP, but the problem is that with some dates work, an example would be: "02/2/2015" returns true, "20/12/2015" false returns, is a serious problem and I see no error in the code.
Function.
<?php
function check_date($date) {
$open_date = explode('/', $date);
if (count($open_date) == 3) {
if (checkdate($open_date[0], $open_date[1], $open_date[2])) {
return true;
} else {
return false;
}
} else {
return false;
}
}
//$date = "02/2/2015"; // return true !
$date = "20/12/2015"; // return false ?
if(check_date($date)) {
echo "valid";
} else {
echo "invalid";
}
?>
How could solve this problem?
checkdate expects a month, day and year, in that order:
https://secure.php.net/manual/en/function.checkdate.php
If your dates are formatted as day/month/year then you can still use checkdate, you'll just have to change the order of the parameters:
if (checkdate($open_date[1], $open_date[0], $open_date[2]))
The signature of checkdate function looks like checkdate(month,day,year); . You can have upto 12 months and not 20. :-)

Date Regular Expression Not Returning True

For some reason this is always returning false... when entering "2014 12 12" into the form. It is this format to enter into a database.
$date = trim($_POST['date']);
in my library.php i have :
function validateDate($date) {
if(preg_match('/^[0-9]{2,4}[\-[[:space:]]]{1}[0-9]{1,2}[\-[[:space:]]]{1}[0-9]{1,2}$/',$date)){
return true;
}
else{
return false;
}
}
and in my php i have :
if (validateDate($date)){
$dateCSS = 'style="border-color: #98faad;"';
}
else {
$dateCSS = 'style="border-color: red;"';
$flag = false;
}
Try this regexp:
^[0-9]{2,4}[\-[:space:]]{1}[0-9]{1,2}[\-[:space:]]{1}[0-9]{1,2}$
A more reliable way to validate a date is to use the datetime extension.
function validateDate($date, $format = 'Y d m') {
return \DateTime::createFromFormat($format, $date) !== false;
}
This way you do not have to resort to using regular expressions, and you will be able to actually validate dates correctly (for example, something like 2014 12 51 will not validate).
if ( ! validateDate('2014 12 51')) {
echo 'Not valid!';
}
It will also allow you to validate more complicated dates, if you will be required to do that some day:
if (validateDate('16th September 2014', 'dS F Y')) {
echo 'Valid!';
}
For the $format argument you must use the formatting options that DateTime::createFromFormat() accepts.

PHP Validation of date format using regex

When a user enters a date in text box,i've to check ,whether it is in yyyy-mm-dd format.
Note Even month,date,for eg:2012-02-32 is not valid because,date can be only till 31 and same for month,he can n't enter month as 13.
If it is in wrong format,i should echo.
Thanks in advance!
Try this
list($year,$month,$day) = explode('-', $input);
if (checkdate($month, $day, $year)) {
// Correct
} else {
// Incorrect
}
Reading comments on http://php.net/manual/en/function.checkdate.php is quite informative, including validating through regexp.
I use the following code from that page:
function checkDateTime($data) {
if (date('Y-m-d', strtotime($data)) == $data) {
return true;
} else {
return false;
}
}
Also I'd recommend adding JavaScript datepicker http://jqueryui.com/demos/datepicker/
$e = explode('-', '2012-02-32');
if (checkdate($e[1], $e[2], $e[0])){
// Valid
}else{
// Invalid
}
http://php.net/manual/en/function.checkdate.php
that's exactly what you need: http://php.net/manual/en/function.checkdate.php
You should not use regular expressions for this. A better (maybe not the best) is to use checkdate();
$parts = explode('-', $input);
if (sizeof($parts) == 3 && checkdate($parts[1], $parts[2], $parts[0])) {
// Correct
} else {
// Incorrect
}

Detecting negative numbers

I was wondering if there is any way to detect if a number is negative in PHP?
I have the following code:
$profitloss = $result->date_sold_price - $result->date_bought_price;
I need to find out if $profitloss is negative and if it is, I need to echo out that it is.
if ($profitloss < 0)
{
echo "The profitloss is negative";
}
Edit: I feel like this was too simple an answer for the rep so here's something that you may also find helpful.
In PHP we can find the absolute value of an integer by using the abs() function. For example if I were trying to work out the difference between two figures I could do this:
$turnover = 10000;
$overheads = 12500;
$difference = abs($turnover-$overheads);
echo "The Difference is ".$difference;
This would produce The Difference is 2500.
I believe this is what you were looking for:
class Expression {
protected $expression;
protected $result;
public function __construct($expression) {
$this->expression = $expression;
}
public function evaluate() {
$this->result = eval("return ".$this->expression.";");
return $this;
}
public function getResult() {
return $this->result;
}
}
class NegativeFinder {
protected $expressionObj;
public function __construct(Expression $expressionObj) {
$this->expressionObj = $expressionObj;
}
public function isItNegative() {
$result = $this->expressionObj->evaluate()->getResult();
if($this->hasMinusSign($result)) {
return true;
} else {
return false;
}
}
protected function hasMinusSign($value) {
return (substr(strval($value), 0, 1) == "-");
}
}
Usage:
$soldPrice = 1;
$boughtPrice = 2;
$negativeFinderObj = new NegativeFinder(new Expression("$soldPrice - $boughtPrice"));
echo ($negativeFinderObj->isItNegative()) ? "It is negative!" : "It is not negative :(";
Do however note that eval is a dangerous function, therefore use it only if you really, really need to find out if a number is negative.
:-)
if(x < 0)
if(abs(x) != x)
if(substr(strval(x), 0, 1) == "-")
You could check if $profitloss < 0
if ($profitloss < 0):
echo "Less than 0\n";
endif;
if ( $profitloss < 0 ) {
echo "negative";
};
Don't get me wrong, but you can do this way ;)
function nagitive_check($value){
if (isset($value)){
if (substr(strval($value), 0, 1) == "-"){
return 'It is negative<br>';
} else {
return 'It is not negative!<br>';
}
}
}
Output:
echo nagitive_check(-100); // It is negative
echo nagitive_check(200); // It is not negative!
echo nagitive_check(200-300); // It is negative
echo nagitive_check(200-300+1000); // It is not negative!
Just multiply the number by -1 and check if the result is positive.
You could use a ternary operator like this one, to make it a one liner.
echo ($profitloss < 0) ? 'false' : 'true';
I assume that the main idea is to find if number is negative and display it in correct format.
For those who use PHP5.3 might be interested in using Number Formatter Class - http://php.net/manual/en/class.numberformatter.php. This function, as well as range of other useful things, can format your number.
$profitLoss = 25000 - 55000;
$a= new \NumberFormatter("en-UK", \NumberFormatter::CURRENCY);
$a->formatCurrency($profitLoss, 'EUR');
// would display (€30,000.00)
Here also a reference to why brackets are used for negative numbers:
http://www.open.edu/openlearn/money-management/introduction-bookkeeping-and-accounting/content-section-1.7
Can be easily achieved with a ternary operator.
$is_negative = $profitloss < 0 ? true : false;
I wrote a Helper function for my Laravel project but can be used anywhere.
function isNegative($value){
if(isset($value)) {
if ((int)$value > 0) {
return false;
}
return (int)$value < 0 && substr(strval($value), 0, 1) === "-";
}
}

Categories