PHP date format error - php

I have an array with a key timestamp with the following content
"timestamp" => "2011-11-29 00:00:00"
When i try to change the format using this
date("F j, Y", $data['Visitor']['timestamp']);
i get the following error
A non well formed numeric value encountered

You should be using the strtotime on the datetime data to convert it into Unix timestamp first.
date("F j, Y", strtotime($data['Visitor']['timestamp']));
Checkout the documentation of date it accept a Unix timestamp as a second parameter and you are passing a datetime value.
DEMO

The function requires the Unix Time which is numeric - and not a string formatted date.
As #Shakti Singh mentions you should use strtotime for that.
From the PHP docs on the timestamp parameter:
The optional timestamp parameter is an integer Unix timestamp that
defaults to the current local time if a timestamp is not given. In
other words, it defaults to the value of time().

A newer way to do this as of PHP 5.2 is the DateTime class:
$datetime = new DateTime('2011-11-29 00:00:00');
echo $datetime->format('F j, Y');
See it in action

Related

PHP: how to create date before the Epoch (1970) using Date instead of DateTime?

In my PHP script I've got a function handling birthdays like so:
$dateTime = \DateTime::createFromFormat('U', $time);
The problem is that this returns false with negative $time numbers (i.e. dates before 1-1-1970). In the PHP docs there's a comment saying that indeed
Note that the U option does not support negative timestamps (before
1970). You have to use date for that.
I'm unsure of how to use Date to get the same result as DateTime::createFromFormat() gives though. Does anybody have a tip on how to do this?
If you just need to format a UNIX timestamp as a readable date, date is simple to use:
// make sure to date_default_timezome_set() the timezone you want to format it in
echo date('Y-m-d H:i:s', -12345);
If you want to create a DateTime instance from a negative UNIX timestamp, you can use this form of the regular constructor:
$datetime = new DateTime('#-12345');

How to properly format/convert datetime based on current locale?

I have this code:
$dateTime = new DateTime('#'.strtotime('+30 minutes'));
$dateTime->setTimezone(new DateTimeZone($someModel->timezone));
$otherModel->send_at = $dateTime->format($otherModel->getDateTimeFormat());
Where $otherModel->getDateTimeFormat() returns M/d/yy h:mm a which is fine because it is based on the current Yii locale which is based on CLDR as far as i know.
Now, when i pass this format to PHP's DateTime::format() class method [$dateTime->format($otherModel->getDateTimeFormat())] i get this result: Dec/06/1313 03:1212 pm which is looking weird because the format that php accepts for date/datetime is not the same as the one Yii is using in it's locales.
How should one fix such issue?
This is the fix:
$dateTime = new DateTime('#'.strtotime('+30 minutes'));
$dateTime->setTimezone(new DateTimeZone($someModel->timezone));
// get a timestamp from the current date that also knows about the offset.
$timestamp = CDateTimeParser::parse($dateTime->format('Y-m-d H:i:s'), 'yyyy-MM-dd HH:mm:ss');
// now format using Yii's methods and format type
$otherModel->send_at = Yii::app()->dateFormatter->formatDateTime($timestamp, 'short', 'short');
The idea is to use the PHP's DateTime::format() method to extract the timestamp that has taken into consideration the user timezone. Then, based on this timestamp, format according to Yii datetime formatting.
Well, nothing strange, your date format is M/d/yy h:mm a, and according to DateTime::format() documentation :
M : A short textual representation of a month, three letters
y : A two digit representation of a year
...etc
Yii does not use the same format :
http://www.unicode.org/reports/tr35/tr35-dates.html#Date_Format_Patterns
You should simply use CDateFormatter::format() : http://www.yiiframework.com/doc/api/1.1/CDateFormatter#format-detail

Convert specific string to time in PHP

I need to convert a string into date format, but it's returning a weird error. The string is this:
21 nov 2012
I used:
$time = strtotime('d M Y', $string);
PHP returned the error:
Notice: A non well formed numeric value encountered in index.php on line 11
What am I missing here?
You're calling the function completely wrong. Just pass it
$time = strtotime('21 nov 2012')
The 2nd argument is for passing in a timestamp that the new time is relative to. It defaults to time().
Edit: That will return a unix timestamp. If you want to then format it, pass your new timestamp to the date function.
To convert a date string to a different format:
<?php echo date('d M Y', strtotime($string));?>
strtotime parses a string returns the UNIX timestamp represented. date converts a UNIX timestamp (or the current system time, if no timestamp is provided) into the specified format. So, to reformat a date string you need to pass it through strtotime and then pass the returned UNIX timestamp as the second argument for the date function. The first argument to date is a template for the format you want.
Click here for more details about date format options.
You are using the wrong function, strtotime only return the amount of seconds since epoch, it does not format the date.
Try doing:
$time = date('d M Y', strtotime($string));
For more complex string, use:
$datetime = DateTime::createFromFormat("d M Y H:i:s", $your_string_here);
$timestamp = $datetime->getTimestamp();

Date and Time functions in PHP & MySQL

I have date and time stored in my database as MySQL DATETIME datatype. While inserting into the database, I am using the following PHP variable
$serverTime = strftime("%Y-%m-%d %H:%M:%S",$_SERVER['REQUEST_TIME']);
A sample DATETIME stored in database is: 2011-11-26 01:00:27
Now my website needs the date to be displayed in the following format: November 26, 2011 (time is not required)
How can I do it? I am trying the below in PHP but wrong output I am getting.
echo strftime("%B %d, %Y",$serverTime)
The PHP strftime() function wants input to be a 32-bit integer timestamp, which is the number of seconds since 1970-01-01 00:00:00.
The default output format for MySQL datetime is YYYY-MM-DD HH:MM:SS. When you use this string in PHP, the leading digits are converted into the integer 2011, which is interpreted to be within the first hour of 1970-01-01.
So you must fetch the datetime from MySQL in another format. Choices:
UNIX_TIMESTAMP(datetime_column) to fetch the datetime as an integer that you can give to PHP's strftime() function.
DATE_FORMAT('datetime_column', '%M %d, %Y') to format the datetime as a string, and then you don't have to use strftime() to format it.
While I would recommend a completely SQL approach, you can use PHP's DateTime class to process your string in PHP (assuming you're running PHP > 5.3):
// Pick a valid TimeZone
$date_obj = DateTime::createFromFormat( 'Y-m-d H:i:s', '2011-11-26 01:00:27', new DateTimeZone( 'America/New_York'));
echo $date_obj->format('F d, Y');
Demo

UNIX Time stamp and MYSQL

I am storing the date of entry in mysql via TIMESTAMP and default value UNIX_TIMESTAMP, however when I bring it back it's 2011-08-16 11:43:52 and if I try to style it with
<?= date('F j, o', $a['time']) ?>
It just does the timestamp from zero, bringing back December 31, 1970
Why? And how can I fix it?
Use
SELECT UNIX_TIMESTAMP(field)
When UNIX_TIMESTAMP() is used on a TIMESTAMP column, the function returns the internal timestamp value directly, with no implicit “string-to-Unix-timestamp” conversion.
Manual
A MySQL TIMSTAMP column is stored as YYYY-MM-DD HH-MM-SS, even if you input a UNIX_TIMESTAMP it will still be stored in that format.
So what you can do is:
<?= date('F j, o', strtotime($a['time'])) ?>
Demo: http://codepad.org/jBLR2KpH
date() takes a number and not a string. MySQL always returns your date as a string regardless of its internal representation. Try this:
<?php echo date("F j, o", strtotime($a['time']); ?>

Categories