php date strtotime wrong unix tuimestamp - php

I am tryig to check timestamp using php. However, the $date variable echoes out a timestamp
1382389873 which I checked with a unix converter epochconverter.com it shows Mon, 21 Oct 2013 21:11:13 GMT when it is meant to be 5 Nov 2013. Anyone can see the code below and pinpount my mistake? Thanks.
$today = strtotime(date("d.m.y"));
$c_date = strtotime($CI->session->userdata('c_date'));
$early = strtotime(date("d.m.y")."+2 week");
$date = strtotime("5.11.13");
echo'<br/>';
echo 'test'.$date;
echo'<br/>';
echo 'collection'.$c_date;
echo'<br/>';
echo 'early'.$early;
echo'<br/>';
echo 'today '.$today;
echo'<br/>';

strtotime is very vague in the way it processes dates. It is interpreting "5.11.13" as 5:11:13pm today (Which is 21:11:13 on a 24-hour clock).
If you want to specify november 5th you should do it like so:
$date = strtotime("11/5/13");
echo $date;
echo date("m/d/Y", $date);
Output:
1383609600
11/05/2013

Others answered this before I did, but here are my tests and notes to supplement the conversation... strtotime() converts a string to a time integer. date() converts an integer to a (optionally formatted) string. I was gonna say you can always just use that rather than epochvonverter.com... but now I understand why you went there. Also note that the manual says this:
"Note: Dates in the m/d/y or d-m-y formats are disambiguated by looking at the separator between the various components: if the separator is a slash (/), then the American m/d/y is assumed; whereas if the separator is a dash (-) or a dot (.), then the European d-m-y format is assumed.
To avoid potential ambiguity, it's best to use ISO 8601 (YYYY-MM-DD) dates or DateTime::createFromFormat() when possible." -http://www.php.net/manual/en/function.strtotime.php (more quirky things on that page, btw).
It is very interesting that this example with dot is NOT producing d.m.y, but h.m.s! I guess that's because we're working with strtoTIME, not... uh.. strtoDATE :)
Consider this:
$integer = 1382389873;
var_dump($integer);
echo "<br>";
//int(1382389873)
$string = date($integer);
var_dump($string);
echo "<br>";
//string(10) "1382389873"
$formatted=date('d.m.y',$integer);
$laterint=strtotime($formatted."+2 week");
var_dump($laterint);
echo "<br>";
// int(1383682213)
$laterstring=date('d.m.y',$laterint);
var_dump($laterstring);
echo "<br>";
// string(8) "05.11.13"
And here's the juicy part:
$date1 = strtotime("5.11.13");
var_dump($date1);
echo "<br>";
$datestring1=date('d.m.y',$date1);
var_dump($datestring1);
//BAD PHP, BAD!
echo "<br>";
$date2 = strtotime("5.11.2013");
var_dump($date2);
echo "<br>";
$datestring2=date('d.m.y',$date2);
var_dump($datestring2);
echo "<br>";
$date3 = strtotime("5/11/13");
var_dump($date3);
echo "<br>";
$datestring3=date('d.m.y',$date3);
var_dump($datestring3);
echo "<br>";
Really interesting stuff, guys - thank you all! The moral of the story for me is to always be explicit with 4 digit year.

I ran a couple of tests for you and it seems that you need to put your year in YYYY format e.g. 2013:
$date = strtotime("5.11.2013"); // your code
echo $date . "\n";
echo date('d-m-Y', $date);
// timestamp: 1383562800
// converted to date: 05-11-2013
--edit-- as I mentioned in my previous comment, if $date is supposed to be the same as $early, why are you even bothering to reassign it manually? Why not just use $early?

Related

why strtotime isn't working on php

I'm trying to compare between two date but unfortunately this isn't working by converting this into UNIX format with strtotime. I'm trying to compare a date to another date.
However this format is working:
if(strtotime("22-04-17") < strtotime("25-05-17")){
echo 'Date One is smaller than date two';
}
But Many times it's failing. I've seen a lot of examples on the web but I can't figure out anything good!
if(strtotime("22-04-17") < strtotime("04-05-17")){ //passing still the
// bigger on but not working
echo 'Date One is smaller than date two';
}
From the manual (make special note of the part I've put in bold):
"Dates in the m/d/y or d-m-y formats are disambiguated by looking at the separator between the various components: if the separator is a slash (/), then the American m/d/y is assumed; whereas if the separator is a dash (-) or a dot (.), then the European d-m-y format is assumed. If, however, the year is given in a two digit format and the separator is a dash (-, the date string is parsed as y-m-d."
So here's what you're doing, with the dates PHP is interpreting your strings as in comments:
// Is 17 April 2022 earlier than 17 May 2025? Yes.
if(strtotime("22-04-17") < strtotime("25-05-17")){
echo 'Date One is smaller than date two';
}
// Is 17 April 2022 earlier than 17 May 2004? No.
if(strtotime("22-04-17") < strtotime("04-05-17")){ //passing still the
// bigger on but not working
echo 'Date One is smaller than date two';
}
I hope this makes the problem you're having clear.
As it also says in the manual, use DateTime::createFromFormat/date_create_from_format if you want to avoid ambiguity:
$date = date_create_from_format('d-m-y', '04-05-17'); // 4 May 2017
your comparsion is not working because strtotime("22-04-17") actually results to timestamp for this date: 17th April 2022;
Do the following and you will see what I mean. the following code will output '2022-May-17`
$date = "22-05-17";
echo date ("Y-M-d ",strtotime($date))."<br>";
Try this
$date1 = date('d-m-y',strtotime("22-04-17"));
$date2 = date('d-m-y',strtotime("04-05-17"));;
if((int)strtotime($date1) < (int)strtotime($date2)){ //passing still the
echo 'Date One is smaller than date two';
}
Your year format 17 causing the problem in strtotime function
I know this isn't what you're looking for but have you tried doing this to showing if date greater / smaller?
// Dates
$Date1 = strtotime("22-04-17 GMT");
$Date2 = strtotime("04-05-17 GMT");
// Diff between dates
$Diff = (int)floor(($Date1 - $Date2) / (60*60*24));
if ($Diff < 0) {
echo "The Diff is negative";
}
Then the other way is like this answer: LINK
$date1 = strtotime("22-04-17 GMT");
$date2 = strtotime("04-05-17 GMT");
if((int)strtotime($date1) < (int)strtotime($date2)){ //passing still the
echo 'Date One is smaller than date two';
}
I wrote a function that takes your datestring and properly return timestmp. Please note that I followed PHP's convention of treating 2 digit years, i.e. 00-69 are mapped to 2000-2069 and 70-99 to 1970-1999
/* functon takes dateString of format dd-dd-yy and return proper timestamp */
function getTimestamp($dateString)
{
$res = preg_match('/^([0-9]{2})\-([0-9]{2})-([0-9]{2})/', $dateString, $matches);
if(!$res)
return 0;
//00-69 are mapped to 2000-2069 and 70-99 to 1970-1999
if($matches[3]>=70 && $matches[3]<=99 )
$year = "19".$matches[3];
else
$year = "20".$matches[3];
$formatted_dat_string = $year."-".$matches[2]."-".$matches[1];
return strtotime($formatted_dat_string);
}
getTimestamp("22-04-99");
So you can now use this function instead of strtotime for comparison.
Finally, I got the solution. The strtotime() isn't any good to handle this case. You should go for dateTime object instead.
//First you need to pass the original format then you will need to pass new
//Format to get this working properly. Hope this will help you guy's
$myDateTimestart = DateTime::createFromFormat('d-m-Y', $dateString);
$startDate = $myDateTimestart->format('m-d-Y');
//with Simply that you can format your date properly
I just Messed my times with this thing it was really bad

Why can't DateTime parse dd.mm.yy always correct?

I've encountered this weird issue:
$date1 = new DateTime('10.10.04');
$date2 = new DateTime('25.03.07');
echo $date1->format('Y-m-d'); // result: 2016-02-15
echo "<br>";
echo $date2->format('Y-m-d'); // result: 2007-03-25
Since the format is the same, I can't explain why the first attempt fails, but the second one succeeds. Is there something that I can do about that?
I can't change the format of the date I receive, so I somehow must read the dd.mm.yy date format to finally format it into the Y-m-d format.
Searched around for something related that helps me, but I couldn’t find anything.
Taken from the documentation, this should be the behavior:
whereas if the separator is a dash (-) or a dot (.), then the European d-m-y format is assumed.
As everyone suggested, try using DateTime::createFromFormat(). Please check below code:
<?php
$date1 = DateTime::createFromFormat('d.m.y','10.10.04');
$date2 = DateTime::createFromFormat('d.m.y','25.03.07');
echo $date1->format('Y-m-d'); // result: 2004-10-10
echo $date2->format('Y-m-d'); // result: 2007-03-25
?>
Output: https://eval.in/518801

PHP date conversion from user input

I am trying to convert a user inputted date so I can use it to search in MySQL. This is my code -
<form name="date_form" action="" method="POST"">
<input type="text" name="start_date" value="<?php echo date('d/m/Y');?>"/>
<input type="submit" name="submit_start" value="Submit" />
<?php
if(isset($_POST["submit_start"]))
{
$date_1 = mysqli_real_escape_string($dbc, trim($_POST['start_date']));//checking that I am getting something from the input
$newDate = date("Y-m-d", strtotime($_POST['start_date']));//converting date from the input to SQL format
echo '<br>date 1 = '.$date_1.'<br>';
echo 'date 2 = '.$newDate.'<br>';
$start_date = '2013-12-13';
echo 'date 3 = '.$start_date.'<br>';//Just to compare formats
$report = create_user_report($dbc, $start_date);
}
and this is the output
date 1 = 14/12/2013
date 2 = 1970-01-01
date 3 = 2013-12-13
2013-12-13
I was expecting date 2 to be 2013-12-13, the format appears to be ok but the value isnt. I have played with many different ways of getting the value, all have been wrong!
So I have two questions please
1. How can I get the correct value in the code above?
2. I want to use this value to search a MySQL table and return a count of dates that match it. Once the above is working, is that the best way to do it - or is there a better way?
Many thanks
From the strtotime manual:
Dates in the m/d/y or d-m-y formats are disambiguated by looking at the separator between
the various components: if the separator is a slash (/), then the American m/d/y is
assumed; whereas if the separator is a dash (-) or a dot (.), then the European d-m-y
format is assumed.
So:
$newDate = date("Y-m-d", strtotime($_POST['start_date']))
is asking for the 12th day of the 14th month.
Try replacing the / with -
$date = str_replace ( '/' , '-' , $_POST['start_date'])
The problem is caused because when confronted with /, strtotime assumes the time to be in the American format of m/d/Y (instead of d/m/Y). Read the manual on strtotime (especially the Notes) for more information.
And because 14/12/2013 is not valid in the American format, you'll get the default time (aka UNIX timestamp 0).
Since this is user input and you cannot be sure if he really means to use the American format or is misusing it, you could do a check before the conversion like this
//check if input is a date in the American format
if (preg_match("#^(\d+)/(\d+)/(\d+)$#", $_POST['start_date'], $matches)) {
if ($matches[1] > $matches[2]) {
$day = $matches[1];
$month = $matches[2];
} else {
$day = $matches[2];
$month = $matches[1];
}
$start_date = $month.'/'.$day.'/'.$matches[3];
}
However if a user inputs e.g. 04/05/2013 this will be interpreted in the American format, although the user could have meant it in d/m/Y.
"Explode" seems to be commonly used in situations like this.
$mydate = $_POST["submit_start"];
list ($y, $m, $d) = explode('/', $mydate);
$mydate = sprintf("%02d-%02d-%04d", $m, $d, $y);
strtotime requires the English date format as input - HERE.
strtotime() PHP Manual
Take a look over there, it reports
The function expects to be given a string containing an English date format
And that's why your function doesn't work as you expect. In fact, d/m/Y is NOT an american date format. Here, take a look, I made you some examples to let you see how to make it work: Click here - eval.in
<?php
echo strtotime(date('m/d/Y'));
echo strtotime(date('d/m/Y'));
echo strtotime(date('d-m-Y'));
echo strtotime(date('d/m/Y'));
echo strtotime(date('Y-m-d'));
echo strtotime(date('Y/m/d'));
?>
Produces
1386979200
FALSE
1386979200
FALSE
1386979200
1386979200
Since you'll never know what kind of date format (or if it's actually a date at all) an user may input, I suggest you to use a date picker plugin on your input, that'll be very useful, or you may want to use a regular expression that other user suggested.
For the mysql part you can easly compare two dates with the MySQL Date Function
Since I don't know your query I'll just provide you the part you need for the comparsion in the query:
... WHERE DATE(some_date) = DATE(some_other_date) ...
Where some_date and some_other_date are two valid date formats as written above.

How to use PHP's strtotime

I'm new to PHP and kind of struggling with the basics, please excuse the horrible code to come.
What I'm trying to do is parse a date retrieved from an XML file, and see if that date falls on a Monday/Tuesday/etc.
I can't seem to get it right, any help is much appreciated.
<?php
foreach ($xml as $x)
{
$time = strtotime($x->Start);
echo $time;
if(date('D', $time) === 'Mon')
echo "Booking for Monday";
else if(date('D', $time) === 'Tue')
echo "Booking for Tuesday";
else if(date('D', $time) === 'Wed')
echo "Booking for Wednesday";
else if(date('D', $time) === 'Thu')
echo "Booking for Thursday";
else if(date('D', $time) === 'Fri')
echo "Booking for Friday";
}
?>
$time isn't outputting anything, and the only result coming back is "Booking for Thursday" for each XML record (x5) despite only two of the records falling on a Thursday.
If I output the results by:
echo $x->Start;
That works fine and outputs "15/07/2013 9:30:00 a.m.".
Cheers!
The date looks like European format d-m-y and uses American format m/d/y seperator.
Note:
Dates in the m/d/y or d-m-y formats are disambiguated by looking at
the separator between the various components: if the separator is a
slash (/), then the American m/d/y is assumed; whereas if the
separator is a dash (-) or a dot (.), then the European d-m-y format
is assumed.
Instead of
$time = strtotime($x->Start);
Try
$time = strtotime(str_replace('/','-',$x->Start));
Additional Info :PHP Manual
you have to convert your time string($x->Start) to one of the Supported Formats before passing it to the strtotime.
Replacing / with . would change your date to a support format. but double check to be sure.
$time = strtotime(str_replace('/', '.',$x->Start));
I see you already have an accepted answer, but I would strongly recommend that you take a look at PHP's DateTime classes. They are extremely useful and can make seemingly complex date operations trivial.
In your particular case, I would replace:-
$time = strtotime($x->Start);
with:-
$time = \DateTime::createFromFormat('d/m/Y H:i:s a', $x->Start);
You can then format the date as you wish using the \DateTime::format() method.

PHP: date function to get month of the current date

I want to be able to figure out the month of the current date variable. I'm ex vb.net and the way to do it there is just date.Month. How do I do this in PHP?
Thanks,
Jonesy
I used date_format($date, "m"); //01, 02..12
This is what I wanted, question now is how do I compare this to an int since $monthnumber = 01 just becomes 1
See http://php.net/date
date('m') or date('n') or date('F') ...
Update
m Numeric representation of a month, with leading zeros 01 through 12
n Numeric representation of a month, without leading zeros 1 through 12
F Alphabetic representation of a month January through December
....see the docs link for even more options.
What does your "data variable" look like? If it's like this:
$mydate = "2010-05-12 13:57:01";
You can simply do:
$month = date("m",strtotime($mydate));
For more information, take a look at date and strtotime.
EDIT:
To compare with an int, just do a date_format($date,"n"); which will give you the month without leading zero.
Alternatively, try one of these:
if((int)$month == 1)...
if(abs($month) == 1)...
Or something weird using ltrim, round, floor... but date_format() with "n" would be the best.
$unixtime = strtotime($test);
echo date('m', $unixtime); //month
echo date('d', $unixtime);
echo date('y', $unixtime );
as date_format uses the same format as date ( http://www.php.net/manual/en/function.date.php ) the "Numeric representation of a month, without leading zeros" is a lowercase n .. so
echo date('n'); // "9"
As it's not specified if you mean the system's current date or the date held in a variable, I'll answer for latter with an example.
<?php
$dateAsString = "Wed, 11 Apr 2018 19:00:00 -0500";
// This converts it to a unix timestamp so that the date() function can work with it.
$dateAsUnixTimestamp = strtotime($dateAsString);
// Output it month is various formats according to http://php.net/date
echo date('M',$dateAsUnixTimestamp);
// Will output Apr
echo date('n',$dateAsUnixTimestamp);
// Will output 4
echo date('m',$dateAsUnixTimestamp);
// Will output 04
?>
To compare with an int do this:
<?php
$date = date("m");
$dateToCompareTo = 05;
if (strval($date) == strval($dateToCompareTo)) {
echo "They are the same";
}
?>

Categories