Bizarre behaviour of some of my code using strftime() - php

I'm pulling some dates from a DB and using PHP strftime to format them.
Now, everything works as intended, apart that if I use the %A format, which is supposed to give me the full weekday name the function just returns NULL, unless the date happens to be on a weekend, in which case it correctly returns "Saturday" or "Sunday".
All the other formats work, even %a (short weekday name).
It does not seem to depend on the locale I use, nor on the specific format of the date (same problem happens if I just use strftime on mktime.
My only thought is that it's some sort of incredibly weird configuration problem server side, but I'd like to hear if anyone had other ideas about it...
EDIT: some code, although it's pretty much what I have written before...
$id = (int)$_GET['event'];
$res = mysql_query("SELECT date FROM events WHERE event_id=".$id);
$row = mysql_fetch_array($res);
echo strftime("%a %H:%M", $row['date']);
echo strftime("%A %H:%M", $row['date']);
The first echo works fine, returning for instance Thu 15:30, the second returns NULL unless $row['date'] falls on a Saturday or Sunday.
If this may be of any help the code is inside a class, but I can't see how this may affect the result...
EDIT2: This is NOT a problem with the DB or the date format, otherwise the first echo wouldn't work. Also, I can just remove the DB code, and generate the date with mktime or with strtotime and it still doesn't work.
EDIT3 (solution): Found the issue. In Italian, the names of the days end in ì (e.g. lunedì), apart from Saturday and Sunday, which do not have accented letters. The result of the operation was passed to json_encode which apparently doesn't like accented characters... A call to utf8_encode (or to htmlentities) solved the issue.

According to the manual : http://php.net/manual/en/function.strftime.php
If you're passing something other than a timestamp you're doing it wrong. Can't really say why the first one passes and the second one doesn't. Maybe PHP is trying to compensate. In any case, if you have a text time representation, you need to call strtotime() on it first.
EDIT
I ran the following code in my system
$row['date'] = '2011-04-06 08:33:29';
echo strftime("%a %H:%M", $row['date']);
echo '<br>';
echo strftime("%A %H:%M", $row['date']);
And I got this as the output
Notice: A non well formed numeric value encountered in F:\webroot\utils\test.php on line 4
Thu 00:33
Notice: A non well formed numeric value encountered in F:\webroot\utils\test.php on line 6
Thursday 00:33
You should have notices enabled on your system. Changing it to timestamp should solve it.
EDIT 2
...Also, I can just remove the DB code,
and generate the date with mktime or
with strtotime and it still doesn't
work
If you could post the sample that doesn't work we could have a look

In your comments you say that your database contains dates such as 2011-04-06 08:33:29. But the second argument to strftime should be a unix timestamp such as 1302766547, that is the number of seconds since 1970-01-01 00:00:00 GMT. Try this instead:
echo strftime('%a %H:%M', strtotime($row['date']));

Related

STRTOTIME in php returning blank value

The dataset value is returning blank, no error on logfile.
$edate = trim($_POST['txtedate']); //user inputs date 12-01-2021
$int_effective_date = new DateTime(strtotime($edate));
echo "edate:- ".$edate."<br />";
echo "strtotime_edate:- ".strtotime($edate)."<br />";
echo "dateset:- ".strtotime($int_effective_date->format('Y/m/d'));
Result:
edate:- 2021-01-12
strtotime_edate:- 1610389800
dateset:-
To paraphrase #iainn: I'm not 100% sure why you're changing back and forth between DateTime objects and function calls to strtotime?
However, I can explain the most likely issue with your code...
strtotime
Firstly, let's clarify that 12-01-2021 is in the format (d-m-Y)? Hopefully it is, in which case PHPs strtotime function understands it correctly and produces a Unix timestamp (i.e. seconds passed since start of 1970)...
strtotime("12-01-2021");
// Output: 1610409600
// Notes:
// - Possible slight variations based on locale etc.
// - Lookup: date_default_timezone_set
// - This is with "UTC"
DateTime
You then pass that timestamp to DateTime but neglect to inform DateTime what kind of timestamp it is...
$int_effective_date = new DateTime(strtotime($edate));
// Is the same as...
$int_effective_date = new DateTime(1610409600);
However, DateTime doesn't see your timestamp as incorrect and tries to process it anyway...
In the format: HisYmd
But your input is too short for that so it only matches HisY
Time => 16:10
Year => 9600
Given the lack of data DateTime then fills in the blanks with today (example: 2021-02-05)
Day => 05
Month => 02
Which give you a complete timestamp of: 9600-02-05 16:10:40
strtotime from DateTime
Your next line of code then passes that timestamp back into a strtotime call...
echo "dateset:- ".strtotime($int_effective_date->format('Y/m/d'));
// Is the same as...
echo "dateset:- ".strtotime("9600/02/05");
Now, strtotime will always return something. Which means the first problem is that you're using echo which doesn't output (bool) false.
Try:
var_dump(strtotime("9600/02/05"));
You might ask, why doesn't that happen in the linked code example from #El_Vanja?
Answer
The answer to that, I believe, is that your PHP version is not up to date and anything over the 32 bit date range is going to return (bool) false from strtotime.
To fix this specific problem I suggest you update your PHP version (and OS if you haven't moved to 64 bit!)
However, further to that, I strongly suggest you stick to the DateTime object/class. It saves you from all of these annoying bugs if nothing else...
For reference:
echo strtotime( (new DateTime("#1610409600"))->format("Y-m-d") ); // Output: 1610409600
echo strtotime( (new DateTime("2021-01-12"))->format("Y-m-d") ); // Output: 1610409600

Timestamp Difference and Output

In My SQL Database I have a Timestamp Column with values like this one representing the Date of the last edit:
2015-01-17 08:55:34.000000
I want to compare the Date with the current date and when is the same day I want to echo Today and otherwise I want to Display the Date of the last edit:
$timefromdb = '2015-01-17 08:55:34.000000'
$edit = strtotime($timefromdb);
if($edit > $_SERVER['REQUEST_TIME']){echo "Today";}
else{
echo strftime("on %A, the %d %B %Y", $edit);
}
echo " at ".date('h:i',$edit)
It always Displays 01/01/1970. There must be a Problem with strtotime. I did a bit of research and it seems like my Timestamp Format isn't a valid one: http://php.net/manual/en/datetime.formats.php
Around the web are a lot of Questions about converting Timestamps but I just can't find the right one: I also got a bit confused by all the functions to convert date stuff.
So can someone Tell me how to get a valid Timestamp for using it in strftime and to compare it to the REQUEST_TIME.
Thanks in Advance!
UPDATE: As Always: The Problem sits in Front of the PC. I declared the Variable but never assgined the Timestamp to it :)
Chop off the .000000 from the date as it makes the date a format strtotime() cannot work with. There's several ways to do this. A simple substr is one of them.
$timefromdb = substr('2015-01-17 08:55:34.000000', 0, -7);
I'm not exactly understood you, but
try
1. compare gettype( $edit ) and gettype($_SERVER['REQUEST_TIME'])
2. not sure what $timefromdb will be more then $_SERVER['REQUEST_TIME'], because IMHO when user edited data, time of it action will me less then current time.

PHP mktime notice

I want to change given date and time or date only into Unix time.
I tried like this:
mktime("Jan-12-2012 2:12pm");
But it’s not working:
Even in PHP documentation I looked at many examples and many of them don’t consist the matter that I want.
And when I try:
$user_birthday=$_POST["user_birthday"];
$db_user_birthday=empty($user_birthday)?"":mktime($user_birthday);
$_POST["user_birthday"] was given value from form that is jan-12-2012 2:12pm
it show error like this:
Notice: A non well formed numeric value encountered in C:\Program
Files (x86)\Ampps\www\admin\index.php on line 76
How do I fix it or display time into Unix?
Use this one:
date("M-d-Y h:i:s", strtotime($user_birthday));
You should be using strtotime instead of mktime:
Parse about any English textual datetime description into a Unix
timestamp.
So your code would be this:
$user_birthday = $_POST["user_birthday"];
$db_user_birthday = empty($user_birthday) ? "" : strtotime($user_birthday);
Then you can process that date like this to get it formatted as you want it to:
echo date("M-d-Y h:ia", $db_user_birthday);
So your full code would be this:
$user_birthday = $_POST["user_birthday"];
$db_user_birthday = empty($user_birthday) ? "" : strtotime($user_birthday);
echo date("M-d-Y h:ia", $db_user_birthday);
Note I also added spaces to your code in key points. The code will work without the spaces, but for readability & formatting, you should always opt to use cleaner code like this.
You should take a look at this answer: convert date to unixtime php
Essentially, you have mixed up mktime() with strtotime(). strtotime() allows you to parse an English textual string into a Unix timestamp. mktime() constructs a unix datetime based on integer arguments.
For example (again taken from the question above)
echo mktime(23, 24, 0, 11, 3, 2009);
1257290640
echo strtotime("2009-11-03 11:24:00PM");
1257290640

Trying to convert from seconds to date

Okay so I have an array of results from a table, we have a start and end time we are retrieving. the start/end time would look something like this:
1345497551
Now I'm trying to convert this to a real time, for instance 1345497551 might become 2012/05/09 17:23:12 or something. I've found a few things but none seem to work correctly. one solution I tried, according to what someone was saying on another question on here, was
$createdate = date('H:i:s',$numberofsecs);
where $numberofsecs was the time pulled in from the array. but this only ever outputs 17:00:00 repeatedly for every time we had available for testing.
How can I go about making this work correctly?
Assuming that that's a standard unix timestamp string (seconds since midnight 1/1/1970), then you should be able to use date as you mentioned, but just modify the format string:
echo date('Y/m/d H:i:s', $numberofsecs);
The example you mention where you were always getting 17:00:00 could have been because your test cases were all only datestamps, encoded as timestamps, and having an offset from GMT . . .
I have tried below code:
$ts = 1345497551;
$date = new DateTime("#$ts");
echo $date->format('U = Y-m-d H:i:s');
output : 1345497551 = 2012-08-20 21:19:11

why am I getting '4:00' when I'm trying to display time using the date function with php?

I am trying to display a time I have in my database. I managed to have it display a time in the correct format for what I need, but for some reason, it is only displaying '4:00' every time.
Here is my code:
date('g:i', strtotime($row['startTime']))
An example of I have the time displayed in my database is like this: 00:12:30
Why is it showing '4:00' every time?
strtotime expects a datetime format ... you should do
date('g:i', strtotime('01 January 2009 ' . $row['startTime']))
Whats the underlying database, and what datatype does the startTime column have? Peering at the closest php code I have, strtoime works fine with a DATETIME representation in the DB (MySQL).
strtotime converts a date time string to a Unix timestamp.
Perhaps your $row['startTime'] doesn't qualify as a date time string.
None of the examples here discussed a date time string which did not include a date.
The link also said that if strtotime is confused, it returns random results. I would add a few more format characters and see what else is returned.
As noted the problem is the use of strtotime(). The following works on my machine, if it's of any use:
$date_text = $row['startTime']; // assuming the format "00:12:30"
list($hrs,$mins,$secs) = explode(":",$date_text); // in response to the question in the comments
/* the explode() takes the string "00:12:30" and breaks into three components "00","12" and "30".
these components are named, by their order in the array formed by explode(), as $hrs, $mins and $secs.
see: http://us3.php.net/manual/en/function.explode.php
and: http://us3.php.net/manual/en/function.list.php
*/
echo "<p>" . date("g:i",mktime($hrs,$mins,$secs)) . "</p>";

Categories