How to format datetime most easily in PHP? - php

To change 2009-12-09 13:32:15 to 09/12/2009

here:
echo date("d/m/Y", strtotime('2009-12-09 13:32:15'))

You can use strtotime to get the timestamp of the first date, and date to convert it to a string using the format you want.
$timestamp = strtotime('2009-12-09 13:32:15');
echo date('d/m/Y', $timestamp);
And you'll get :
09/12/2009
[edit 2012-05-19] Note that strtotime() suffers a couple of possibly important limitations:
The format of the date must be YYYY-MM-DD; it might work in some other cases, but not always !
Also, working with UNIX Timestamps, as done with date() and strtotime() means you'll only be able to work with dates between 1970 and 2038 (possibly a wider range, depending on your system -- but not and illimited one anyway)
Working with the DateTime class is often a far better alternative:
You can use either DateTime::__construct() or DateTime::createFromFormat() to create a DateTime object -- the second one is only available with PHP >= 5.3, but allows you to specify the date's format, which can prove useful,
And you can use the DateTime::format() method to convert that object to any date format you might want to work with.

Using the date() method.
print date("d/m/Y", strtotime("2009-12-09 13:32:15"));

$long_date = '2009-12-09 13:32:15';
$epoch_date = strtotime($long_date);
$short_date = date('m/d/Y', $epoch_date);
The above is not the shortest way of doing it, but having the long date as an epoch timestamp ensures that you can reuse the original long date to get other date format outputs, like if you wanted to go back and have just the time somewhere else.

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');

Formatting datetime

i am trying to format a datetime which comes fromt he database in the format of
2012-06-11 21:39:54
However i want it to display in the format of June 11
How can do this?
Thanks
echo date('M d', strtotime('2012-06-11 21:39:54'));
Output
You can also use DateTime object.
$date = new DateTime($yourString);
$date->format($yourFOrmat);
I think that it would be the best way because DateTime is really more powerful than timestamp and date/strtotime functions.
From the code I gave above you can add functionalities like modifying dates, iterate over the time, compare 2 dates without functions like str_to_time...
$date->modify('+1 day');//the day after for example
foreach(new DatePeriod($date,new DateInterval('PT1M'),10){
$date->format($yourFormat);//iterate each minute
}
and so on
PHP manual gives an excellent documentation about using Date/Time functions. Basically you will need a combination of two functions: strtotime() and date().
strtotime() will convert your date into Unix timestamp which can be supplied to date() as second argument.
The format of date you will need is: M d.
Alternative: In addition you could also try the MYSQL counterpart which won't require conversion to UNIX timestamp. It is documented here. Assuming you are using date as your Datetime field, you will need something like this,
SELECT id,..,DATE_FORMAT(`date`, '%M %d') as f_date FROM table
For formatting date using php, you need to pass timestamp of date
and format specifiers as arguments into date function .
Eg echo date('M d',strtotime('2012-06-11 21:39:54'));

Function to parse psql timestamp

I display the date or the time on my website a lot and I'm thinking about writing a function to parse a PostgreSQL timestamp.
The timestamp is in the format: Y-m-d H:i:s.u. E.g. 2011-04-08 23:00:56.544.
I'm thinking about something like this:
function parse_timestamp($timestamp, $format = 'd-m-Y')
{
// parse the timestamp
return $formatted_timestamp;
}
However I am wondering whether this can also be achieved without writing a parser for it myself (with the use of some PHP function).
function parse_timestamp($timestamp, $format = 'd-m-Y')
{
return date($format, strtotime($timestamp));
}
Don't forget to set timezone before, e.g.
date_default_timezone_set('UTC');
Or in your case, I guess 'Europe/Amsterdam'.
You can always get PHP timestamp of this format Y-m-d H:i:s.u using strtotime(). Then, using date() you can export time in your own format. Both functions depend of time zone set.
strtotime is perfectly capable of parsing that time string, then just reformat it with date:
echo date('d-m-Y', strtotime('2011-04-08 23:00:56.544')); // 08-04-2011
For those using DateTime class:
DateTime::createFromFormat('Y-m-d H:i:s.u', $yourTime);
If the database isn't giving you what you want, change it. PostgreSQL can also format dates and times.
select to_char(timestamp '2011-03-04 07:04:00', 'DD-MM-YYYY');
04-03-2011
But that's risky in international contexts, like the web. Different locales expect different ordering of elements. (Does "04-03" mean 03-April or 04-March?) This expression is easier to understand, and it uses locale-specific abbreviations for the months.
select to_char(timestamp '2011-03-04 07:04:00', 'DD-Mon-YYYY');
04-Mar-2011
Take a look at the strptime function - it can parse many time formats.

Convert uncommon date format to timestamp in most efficient manner possible?

I have a date in this format: 20101101120000
I need to convert it to a timestamp with PHP.
I've been searching the PHP docs online, but can't find anything that can convert directly. Does one exist? If not, what's the most efficient way to do the conversion? Thank you for your help.
You can do this with DateTime::createFromFormat:
$d = DateTime::createFromFormat('YmdGis', '20101101120000');
$d is now a DateTime instance. You can either convert it to a timestamp with $d->getTimestamp() or use the DateTime methods on it.
Note that this requires PHP 5.3.
strtotime('20101101120000')
....
You need the function strptime.
The formats are described at strftime.
I only add to this resolved question because this may be helpful for users who stumble upon here (like I did) and are looking to get an actual datetime timestamp.
My assumption for most folks when they mention timestamp is that they're looking for a normal "YYYY-MM-DD HH:MM:SS" timestamp not a unix timestamp which you get when you use the getTimestamp() method (see accepted answer if you are indeed looking for the UNIX Timestamp).
So I will further elaborate on lonesomeday's answer (which is fully correct) for those looking to actually get a valid formated date that they can display to users or insert into their database:
$d = DateTime::createFromFormat('YmdGis', '20101101120000');
$formatedDate = $d->format('Y-m-d H:i:s'); // will return 2010-11-01 12:00:00
$formatedDate = $d->format('m-d-Y h:i A'); // will return 11-01-2010 12:00 PM

strtotime of today

Hallo, I want to find the difference between today and another date,
convert todays date into unix time format here
<?php
echo '1st one'.strtotime(date("d.m.Y")).'<br>';
echo '2nd one'.strtotime(date("m.d.Y")).'<br>';
?>
The first echo is producing some value, but not the second one. What is the bug in it...please help..
strtotime makes assumptions based on the date format you give it. For instance
date("Y-m-d", strtotime(date("d.m.Y"))) //=> "2010-09-27"
date("Y-m-d", strtotime(date("m.d.Y"))) //=> "1969-12-31"
Note that when given an invalid date, strtotime defaults to the timestamp for 1969-12-31 19:00:00, so when you end up with an unexpected date in 1969, you know you're working with an invalid date.
Because strtotime is looking for day.month.year when you use . as the delimiter, so it sees "9.27.2010" as the 9th day of the 27th month, which obviously doesn't exist.
However, if you change it to use / as the delimiter:
date("Y-m-d", strtotime(date("d/m/Y"))) //=> "1969-12-31"
date("Y-m-d", strtotime(date("m/d/Y"))) //=> "2010-09-27"
In this case, strtotime expects dates in month/day/year format.
If you want to be safe, Y-m-d is generally a good format to use.
It's worth pointing out that strtotime() does accept words like "today" as valid input, so you don't need to put a call to date() in there if all you want is today's date. You could just use strtotime('today');.
Come to think of it, a simple call to time(); will get you the current time stamp too.
But to actually answer the question, you need to consider that d.m.Y and m.d.Y are ambiguous - if the day of the month is less than the 12th, it is impossible to tell which of those two date formats was intended. Therefore PHP only accepts one of them (I believe it uses m/d/Y if you have slashes, but for dots or dashes it assumes d-m-Y.
If you're using strtotime() internally for converting date formats, etc, there is almost certainly a better way to do it. But if you really need to do this, then use 'Y-m-d' format, because it's much more universally reliable.
On the other hand, if you're accepting date input from your users and assuming that strtotime() will deal with anything thrown at it, then sadly you're wrong; strtotime() has some quite big limitations, of which you've found one. But there are a number of others. If you plan to use strtotime() for this sort of thing then you need to do additional processing as well. There may also be better options such as using a front-end Javascript date control to make it easier for your users without having to rely on strtotime() to work out what they meant.
strtotime does not consider 09.27.2010 to be a valid date...
You could check it like this:
<?php
// will return false (as defined by the docs)
echo var_dump(strtotime("09.27.2010"));
?>
The function expects to be given a string containing a US English date format and will try to parse that format into a Unix timestamp. US time format is : MM DD YYYY
look here for the Information about which formats are valid http://www.php.net/manual/en/datetime.formats.php. But what do you mean with deference between 2 dates? You mean the Timespan between 2 dates?
echo (time() - strotime("- 2 days")) . " seconds difference";
Something like that?
strtotime would not take the d.m.y format. good way is Y-m-d

Categories