if ($this->request->is('post')) {
$this->Operation->create();
if(!isset($this->request->data['Operation']['date_alarma'])){
$this->request->data['Operation']['date_alarma']= date('Y-m-d H:i:s',strtotime($this->request->data['Operation']['date_alarma'].' '.$this->request->data['Operation']['alarmA']['hour'].$this->request->data['Operation']['alarmA']['min']));
}
else if(!isset($this->request->data['Operation']['date_alarmb'])){
$this->request->data['Operation']['date_alarmb']= date('Y-m-d H:i:s',strtotime($this->request->data['Operation']['date_alarmb'].' '.$this->request->data['Operation']['alarmB']['hour'].$this->request->data['Operation']['alarmB']['min']));
}
else if(isset($this->request->data['Operation']['date_alarmcc'])){
pr($this->request->data['Operation']['date_alarmcc']) ;
$a= date('Y-m-d',strtotime($this->request->data['Operation']['date_alarmcc']));
pr($a); die;
}
The output showing like this
30/05/2015
1970-01-01
May I know why? The date I enter is 30/05/2015 at field date_alarmcc
strtotime() will interpret this format as m/d/Y, not d/m/Y and thus will return false because there is no 30th month.
echo (int) strtotime('05/30/2015');
// 1432969200
echo (int) strtotime('30/05/2015');
// 0
However, strtotime() will evaluate d-m-Y:
echo (int) strtotime('05-30-2015');
// 0
echo (int) strtotime('30-05-2015');
// 1432969200
Unix timestamps represent the number of seconds passed from 1970-01-01 so this represents the timestamp 0 because of the false return value from strtotime().
If you always want to use the d/m/Y format. You could easily replace / with - using str_replace():
$date = str_replace('/', '-', $date);
Thus it will be evaluated as d-m-Y correctly.
Related
Hi I have a function that checks to see if a user input string is a valid date. The user has to input the date in the format 25-January-2018 and it checks to see if it can be converted to the format 25-01-2018. However when I test the function using a date where both the month and day are single digits then it returns false even though a valid date has been entered.
function validateDate($date){
$d = DateTime::createFromFormat('d-F-Y', $date);
return $d && $d->format('j-F-Y') === $date;
}
echo validateDate("03-February-2018"); //Returns false when it should be true
You should replace the j-F-Y with d-F-Y.
j means 1 to 31 while d means 01 to 31 then your two formats are different for the given date.
The following code works:
function validateDate($date){
$d = DateTime::createFromFormat('d-F-Y', $date);
return $d && $d->format('d-F-Y') === $date;
}
var_dump(validateDate("03-February-2018"));
Your function could work :
return $d && $d->format('d-F-Y') === $date;
but if your want to check if it's a valid date use this :
DateTime::createFromFormat('d-F-Y', "03-February") // returns false if not a valid date & Object if valid
Use strtotime() function better.
function validateDate($date){
$timestamp = strtotime($date);
$newDate = date('d-F-Y', $timestamp);
return ($timestamp && $newDate);
}
echo validateDate("03-February-2018");
I have converted one variable into unix timestamp to checl whether it is valid date or not
.Format is dd/mm/yy . My code is below
<?php
$date1='24/11/2013';
$date2='09/11/2013';
$date3='yuyuy1909090';//CAN BE ANYTHING
if(strtotime($date1)>0){
echo "valid date1";
}
if(strtotime($date2)>0){
echo "valid date2";
}
if(strtotime($date3)>0){
echo "valid date2";
}
?>
but if says only $date2 is valid, i cannot change the format of date because it comes form 3rd party flat file...
What could be the issue?
If you know the valid format, you can use:
$date = DateTime::createFromFormat('d/m/Y', $date1);
if ( $date->getTimestamp() > 0 ) {
echo 'valid date1';
}
Because strtotime thinks 24/11/2013 is in american format, as dates with slashes are interpreted as m/d/y, and there is no 11th of the 24th month, so it fails.
if you did
strtotime('11/24/2013');
instead, it would work.
If you want to keep your date in that format and still use strtotime, you could do
strtotime(str_replace('/', '-', '24/11/2013'));
as dates with hyphens are interpreted as d-m-y format
when date is $date1='yuyuy1909090' then
$date = DateTime::createFromFormat('d/m/Y', $date1);
if ( $date->getTimestamp() > 0 ) {
echo 'valid date1';
}
In such case it will give error , so better to add one line more for regex validation
if(preg_match("/^\d{1,2}\/\d{1,2}\/\d{4}/",$date1){
$date = DateTime::createFromFormat('d/m/Y', $date1);
if ( $date->getTimestamp() > 0 ) {
echo 'valid date1';
}
}
My $date output is in the foreach loop
09/25/11, 02/13/11, 09/15/10, 06/11/10, 04/13/10, 04/13/10, 04/13/10,
09/24/09, 02/19/09, 12/21/08
My mysql query(PHP) is as follows
("INSERT INTO table_name(`field1`, `field2`,`date`) VALUES ('".$value1."','".$value2 ."','".$date."')");
Question: In my database all the dates stores as 0000-00-00 00:00:00. But 4th date (06/11/10) is stored as 2006-11-10 00:00:00.
I tried with date('Y-m-d H:i:s', $date); but no help.
Note: My database field is datetime type.
Any idea?
You're on the right track with your date('Y-m-d H:i:s',$date); solution, but the date() function takes a timestamp as its second argument, not a date.
I'm assuming your examples are in American date format, as they look that way. You can do this, and it should get you the values you're looking for:
date('Y-m-d H:i:s', strtotime($date));
The reason it's not working is because it expects the date in the YYYY-MM-DD format, and tries to evaluate your data as that. But you have MM/DD/YY, which confuses it. The 06/11/10 example is the only one that can be interpreted as a valid YYYY-MM-DD date out of your examples, but PHP thinks you mean 06 as the year, 11 as the month, and 10 as the day.
I created my own function for this purpose, may be helpful to you:
function getTimeForMysql($fromDate, $format = "d.m.y", $hms = null){
if (!is_string($fromDate))
return null ;
try {
$DT = DateTime::createFromFormat($format, trim($fromDate)) ;
} catch (Exception $e) { return null ;}
if ($DT instanceof DateTime){
if (is_array($hms) && count($hms)===3)
$DT->setTime($hms[0],$hms[1],$hms[2]) ;
return ($MySqlTime = $DT->format("Y-m-d H:i:s")) ? $MySqlTime : null ;
}
return null ;
}
So in your case, you use format m/d/yy :
$sql_date = getTimeForMysql($date, "m/d/yy") ;
if ($sql_date){
//Ok, proceed your date is correct, string is returned.
}
You don't have the century in your date, try to convert it like this:
<?php
$date = '09/25/11';
$date = DateTime::createFromFormat('m/d/y', $date);
$date = $date->format('Y-m-d');
print $date;
Prints:
2011-09-25
Now you can insert $date into MySQL.
I have in issue with this code, I'm reusing it from a different script, it is reading from an xml file and converting the date/time from a node. The date in the node is as follows which is the only difference to the original script:
<od>10:15:41 01/03/13</od>
I thought I had this modified correctly but it isn't working:
$_date=$record->getElementsByTagName("od");
$_date=((!empty($_date))?$_date->item(0)->nodeValue:"");
if(strpos($_date,".")!==false)
{
$_date=substr($_date,0,strpos($_date,"."));
}
$_date=date("H:i:s m/d/Y",strtotime($_date));
$_date.=(trim($_date)!="")?"Z":"";
xmlrpc_set_type($_date, 'datetime');
Any help is much appreciated.
The date/time 10:15:41 01/03/13 is an invalid format.
Use DateTime::createFromFormat instead.
strftime will work fine with a Y-m-d H:i:s format as it's unambiguous.
On the other hand, it gets confused with H:i:s m/d/y, as it can be interpreted as H:i:s d/m/Y. Think about the date 02/03/2013 - m/d/y would suggest that it's the 3rd of Feb, whereas d/m/Y would suggest that it's 2nd of March.
In other words, to ensure we get the right date every time, we have to be more specific. date_create_from_format('H:i:s m/d/y', $_date) will give you a DateTime object corresponding to the correct date, if the date given is indeed in the 'H:i:s m/d/y' format.
// Retrieve the date string
$_date=$record->getElementsByTagName("od");
$_date=((!empty($_date))?$_date->item(0)->nodeValue:"");
// Standardize it
$_date = get_date( $_date );
$_date .= (trim($_date) != "") ? "Z" : "";
xmlrpc_set_type($_date, 'datetime');
function get_date( $rawDate ) {
// Clean date string
if(strpos($rawDate,".")!==false) {
$rawDate=substr($rawDate,0,strpos($rawDate,"."));
}
// Attempt converting from m/d/y AND m/d/Y formats
$date = date_create_from_format('H:i:s m/d/y', $rawDate);
if( false === $date ) $date = date_create_from_format('H:i:s m/d/Y', $rawDate);
if( !empty($date) ) {
return $date->format('H:i:s m/d/Y'); // Convert the date to a string again
}
// If neither works, try using strtotime instead
$date = #strtotime($rawDate);
$date = !empty($date) ? date('H:i:s m/d/y', $date) : false;
return $date;
}
Hope that helps!
I have problem with date function in php. If I supply string in format "d.m.y" for example "01.01.01" it gets rendered as todays date which means that php gets confused.
I found:
Note:
The "Day, month and two digit year, with dots or tabs" format (dd [.\t] mm "." yy)
only works for the year values 61 (inclusive) to 99
(inclusive) - outside those years the time format "HH [.:] MM [.:] SS" has
precedence.
on: php.net site
How to override this behavior?
I know of date_create_from_format function which would work fine if I knew input will always be in format "d.m.y", but it won't.
UPDATE 1:
Code
$date = new DateTime('01.01.01');
echo $date->format('Y-m-d');
outputs 2010-10-19 and I wanted 2001-01-01.
To format a date other than now, use the second parameter. For example:
echo date("d.m.y", 1255982665);
echoes 19.10.09
Just read the documentation! PHP's site is excellent
It seems like you want to reformat a date?
mktime() gives unix timestamp from component pieces
date() gives string from unixtimestamp (or implied now)
getdate() gives assoc array from unix timestamp
I think you want -
$arr = explode($dateIn, ':'); //get array [day, month, year]
$timestamp = mktime(0,0,0, $arr[0], $arr[1], $arr[2]) //unix time stamp, a long integer representing time
date(DESIREDFORMAT, $timestamp);
check out the output formats here - http://us2.php.net/manual/en/function.date.php
function getDateFromString( $str )
{
$date = DateTime::createFromFormat( 'd.m.y', $str );
if ( $date !== false )
return $date->getTimestamp();
// you can try other common formats here
// ...
// otherwise just parse whatever there is
return strtotime( $str );
}
echo date( 'd.m.Y H:i', getDateFromString( '01.01.01' ) ); // 01.01.2001 20:14
Edit
To adjust it a bit more to get your exact output:
function getDateTimeFromString( $str )
{
$date = DateTime::createFromFormat( 'd.m.y', $str );
if ( $date !== false )
return $date;
// you can try other common formats here
// ...
// otherwise just parse whatever there is
return new DateTime( $str );
}
$date = getDateTimeFromString( '01.01.01' );
echo $date->format( 'Y-m-d' ); // 2001-01-01