PHP convert string with weeks and short month name to date - php

I am receiving JSON data with a date string with this format:
'Mon Jun 30, 2014'
What would be the way to convert this to a datetime? Checking the PHP functions for this I got unsecure if better to use date_parse_from_format or date_create_from_format.
What are the differences and which would suit better for this task?

DateTime::createFromFormat would work well here. It allows you to format the string easily and also takes timezones into consideration when appropriate and can be easily used in comparisons without having to convert to a timestamp first.
$date = DateTime::createFromFormat('D M d, Y', 'Mon Jun 30, 2014');
echo $date->format('Y-m-d');

You can convert to a unix timestamp using strtotime(). I don't know what you mean by a "datetime", but if you mean something like for MySQL then you format the timestamp with date() (you can include time but it isn't present in the original string):
echo date('Y-m-d', strtotime($string));

The second of the two likely fits you better ---
The first one only breaks down the date into an array, so you can work with the parts, individually.
But the second returns the DateTime object you are looking for.

Related

How to format date in PHP from a string of concatenated numbers?

I am new to PHP and I am trying to learn more of php date and time but I seem to get stuck with this.
I have this date format:
ddMMyyHHmmss
And an example is 120813125055 but I am trying to manipulate the string such that it will give me the format of:
yyyy-MM-dd HH:mm:ss (in the example above, 2013-08-12 12:50:55)
I tried to do something like:
date('Y-m-d H:i:s', strtotime('120813125055'));
But it always gives me a result of 1969-12-31 18:00:00.
I assume that I need to do some string manipulation in PHP for this but I was wondering if there is an easier and more efficient way to do it?
I think what you're looking for is in the second response answered here: how to re-format datetime string in php?
To summarize (and apply to your example), you could modify the code like this.
$datetime = "120813125055";
$d = DateTime::createFromFormat("dmyHis", $datetime);
echo $d->format("Y-m-d H:i:s");
Use date_create_from_format:
$ts = date_create_from_format('dmyHis', '120813125055');
$str = date('Y-m-d H:i:s', $ts);
strtotime() only works on EASILY recognizable formats. Your is a ugly mix of garbage, so no surprise that strtotime bails with a boolean FALSE for failure, which then gets typecast to an int 0 when you tried feed it back into date().
And of course, note that your time string is NOT y2k compliant. two digit years should never ever be used anymore, except for display purposes.
You're using your function call and the argument the wrong way around.
In your example, php will try to return you the date for which the time is 'strtotime('120813125055')', and this function returns false (interpreted as 0). So you get returned the date formatted in 'Y-m-d H:i:s' for the Unix epoch.
You will need to get the actual timestamp of your string, so use http://www.php.net/manual/en/datetime.createfromformat.php.
You are mistaken here..
I tried to do something like:
date('Y-m-d H:i:s', strtotime('120813125055'));
You shouldn't use only numbers ( doesnt matter its an integer or a string ), than it will always give you the same thing.
You can use any other valid date and time ( E.G. 6 Jun 2013, 5 may 12...) . Because what strtotime() do is detect a valid date and convert it into timestamp.

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

How to make date time like this?

Hi I am saving data from rss feed url. From that me got date time like this.
Sun, 2 January 2011 03:04:02 GMT+5:30
How to change this date to this format 2nd January 2011, 03:04 PM using php?
any body knows the solution please help me.
You can se the strtotime function to convert the existing string and the 'r' specifier to the date function as follows (looks like you want it in RFC 2822 format, if not tweak accordingly):
date('r', strtotime("Sun, 2 January 2011 03:04:02 GMT+5:30"));
Incidentally, make sure you're setting your local timezone correctly via date_default_timezone_set, etc.
The following functions are useful for taking a string and getting a timestamp back:
strtotime()
DateTime::createFromFormat()
After you have it as a timestamp, you can reformat it using date(). I'm not 100% sure if strtotime() would accept that format, but it should accept it because the format it isn't ambiguous.
echo date("js F Y, h A", strtotime($oldDate));

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

How to format datetime most easily in 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.

Categories