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';
}
}
Related
I have a situation where I need to create a Datetime object from a string.
The issue comes when I don't have consistency in the pattern of the string representing the date.
These are examples of my data:
07/17/2012
2013/03/11
17/05/2015
17/17/2015
As you can see, the last one is invalid no matter what, because there is no 17 month, but the first 3 are valid depending on the month position(and of course, the year)
My question: is there any way(pretty sure through regex) to make a function with the date string as parameter that return the datetime object. If the string is not valid, return: 1/1/1970...
The issue comes when I don't have consistency in the pattern of the string representing the date
for this purpose, php offers strtotime(): http://php.net/manual/en/function.strtotime.php
Example usage:
$str1 = "2015-06-04 16:00";
$str2 = "06/04/2015 4 pm";
$str3 = "04.06.2015 16:00";
$actualDate = date("Y-m-d H:i:s", strtotime($str1));
echo $actualDate."<br />";
$actualDate = date("Y-m-d H:i:s", strtotime($str2));
echo $actualDate."<br />";
$actualDate = date("Y-m-d H:i:s", strtotime($str3));
echo $actualDate."<br />";
//all will produce "2015-06-04 16:00:00"
as a bonus, strtotime also supports "insane" expressions like
$actualDate = date("Y-m-d H:i:s", strtotime("06/04/2015 + 1 day - 8 hours"));
echo $actualDate."<br />";
// "2015-06-04 16:00:00"
and many more such as "monday this week", "tuesday next week", "first monday of january 2038" and the like.
You can try to create DateTime Object with your string values. It will throw exception if the date format is not valid, then you can just catch it and return your 1/1/1971
try {
$dateTime = new DateTime('17/17/2015');
return $dateTime;
} catch (Exception $e) {
return '1/1/1971';
}
You can use DateTime.
$myDate = '17/17/2015';
$date = DateTime::createFromFormat('d/m/Y', $myDate);
if (DateTime::getLastErrors()['warning_count'] >= 1) {
// Invalid
} else {
// Valid date
}
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.
here i am checking the date with current date to previous date it show the proper message when the subtracted date's result is current date .but when the subtracted result is previous date like 02-12-2014 - 4 days it gives 28-11-2014 .and condition of (02-12-2014>=28-11-2014) it gives false.why it cant check the diff of diff month's date. even it true the condition when date like (04-12-2014>=06-12-2014).
<div class="box-content">
<div class="maq_cont">
<marquee direction="up" scrollamount="3" onMouseOut="this.setAttribute('scrollamount',3,0)" onMouseOver="this.setAttribute('scrollamount', 0, 0)" style="height:200px; margin-top:-10px; margin-bottom:-10px;">
<ul class="maq_li">
<?php
echo $work_date = "03-12-2014";
echo "<br>";
echo $day = "3";
echo "<br>";
echo $show_date = date( "d-m-Y", strtotime( "$work_date -$day day" ));
echo "<br>";
echo $cur_date= date( "d-m-Y" );
if ($cur_date >= $show_date) {
echo '<li>done</li>';
} else {
echo '<li>not done</li>';
}
?>
</ul>
</marquee>
</div>
</div>
Try with -
if(strtotime($cur_date)>=strtotime($show_date)){
It is happening because they are strings.
You have to put the year at the beginning of your date string, then month and then the day. The reason is: You aren't comparing dates, you compare string. And they will be compared alphabetically.
e.g. the string date '01.01.2015' is alphabetically smaller than '02.01.2013', but this format ('Ymd') does the trick in this special order: '20150101' is alphabetically and also numerically greater than '20130102'.
// this formatting will work
$show_date = date('Ymd', strtotime("$work_date -$day day"));
$cur_date = date('Ymd');
I would prefer to do this comparison with date and the awesome DateTime object. Do it like this:
if (new DateTime('NOW')
>= DateTime::createFromFormat('d-m-Y', $show_date))
{
echo '<li>done</li>';
} else {
echo '<li>not done</li>';
}
The DateTime::createFromFormat() call returns a DateTime object. The first parameter $format has the same syntax like your format string you are using with date(). The second parameter is the so formatted date string to parse. Read more:
http://php.net/manual/en/datetime.createfromformat.php
After getting this DateTime object you can do some magic like
$date = DateTime::createFromFormat('d-m-Y', $show_date);
$date->modify('+1 days'); // one day later
And to output the date as string use the format()function:
$date->format('Y'); // the year
$date->format('m'); // the month
$date->format('d'); // the day
$date->format('Y-m-d H:i:s'); // e.g. 2014-12-05 23:11:00
$date->format('U'); // as timestamp: 1417817460
// [...]
More Information:
http://php.net/manual/en/datetime.format.php
http://php.net/manual/en/datetime.modify.php
http://php.net/manual/en/function.date.php
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!
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";
}