PHP 6 digit date code display in human readable format - php

I have a set of dates that are formatted like this...
197402
192201
184707
The first four digits represents the year and the remaining two the month. I am trying to output these in this format
February 1974
January 1922
July 1847
I have tried passing it to the date function like this...
echo date ('F Y', 197402)
But this is giving me January 1970 everytime so I assume I have misunderstood how the date function works, can anyone help?

You're getting "January 1970" as an output, because you tried to create a date from the timestamp 197402, which is seconds from January 1st, 1970. If you output the full string from that (with seconds and whatnot), you'll see it's a valid timestamp, producing an actual date, but they all end up in the start of January 1970, see this online demo.
That format, YYYYMM, isn't a recognizable format for most functions. You need to split it up, if you know the format will be in that way - and use that data instead. You can use substr() to split the string, and then convert the numerical month to the string associated with that month, with the help of date() and mktime() (since you just specify the year and month).
The following snippet
$arr = [197402, 192201, 184707];
foreach ($arr as $v) {
$year = substr($v, 0, 4);
$month = substr($v, 4, 2);
echo date("F Y", mktime(0, 0, 0, $month, 0, $year))."<br />"; // mktime() produces a valid timestamp based on just month and year
// Alternatively, drop mktime() and use strtotime() and create from a standard format,
// while specifying a date in the month (which won't matter to the output)
// echo date("F Y", strtotime("$month/01/$year"))."<br />";
}
will output
February 1974
January 1922
July 1847
Alternatively, you can use the DateTime class (which is a lot simpler to work with), and create from a given format with date_create_from_format()
foreach ($arr as $v) {
echo date_create_from_format('Yh', $v)->format('F Y')."<br />";
}
This will generate the same output as above.
References
http://php.net/substr
http://php.net/mktime
http://php.net/date
http://php.net/datetime.createfromformat

I'd use the DateTime class, you can create from a specific format, and then output to another.
As pointed out in the comments below, you also need to set the day to the first of the month, otherwise you'll get undesired results if the current day is greater than the number of days in the given month.
echo DateTime::createFromFormat('Ymd', 19470201)->format('F Y');

As you are passing an int to date, it is considering it as a Unix Timestamp.
To create a date object from a predefined format, use DateTime::createFromFormat.
echo DateTime::createFromFormat('Ym',198403)->format('F Y');
results in
March 1984

You'd need to add a day to it, e.g. just add "01" and then use strtotime to convert that into a unix timestamp, as the date() function expects a timestamp as the parameter.
e.g.
echo date('F Y', strtotime("19220101"));

You have text representation of dates in a non-standard format. First you have to parse them and convert them to timestamps (the number of seconds since Jan 1, 1970 00:00:00 UTC). The PHP function date() can work only with timestamps.
The best approach (as of 2017) is to use the DateTime PHP class for date & time processing:
foreach (array('197402', '192201', '184707') as $text) {
$date = DateTime::createFromFormat('Ym', $text);
echo($date->format('F Y')."\n");
}
The method DateTime::createFromFormat() parses a string using the given format and creates a new DateTime object if the parsing succeeds. It is the OOP equivalent of strtotime() but smarter (because it can get hints about what date components to search in the input string.)
The method DateTime::format() produces the text representation of a date using the provided format. It is the OOP equivalent of date().
The OOP approach (the DateTime* classes) is recommended (and better than the procedural approach) because has built-in support for timezones (the procedural date-time functions lack it.)

Related

Disable over-permissive behavior of DateTime::createFromFormat

Given an invalid date in the format MMDD, say 1332, the DateTime::createFromFormat method in PHP 5.3.0+ will accept it as a valid date, 0201 in that same MMDD format.
Code snippet:
$dateobj = DateTime::createFromFormat("md", "1332");
if ($dateobj) {
print $dateobj->format('Y/m/d H:i:s') . "\n";
}
Output:
2019/02/01 20:59:37
Obviously, 13 is not a valid month of the year and 32 is not a valid day of any month. It's also apparent that DateTime::createFromFormat is "rolling over" those numbers, as if it were adding 13 months and 32 days to a zero value (the current datetime's year). One month after December (month 12) is January (in this case month "13"), and 32 days after January 1 (inclusive) is February 1.
Is there a way to still use DateTime::createFromFormat but disable, override, or otherwise work around that specific over-permissive behavior?
One way to use DateTime::createFromFormat, and it alone, is to compare the DateTime object it created to the original input:
$dateobj = DateTime::createFromFormat($format, $date);
if ($dateobj && $dateobj->format($format) == $date) {
print($dateobj->format($format));
}
If they're the same, the input date is valid. If they're not the same, DateTime::createFromFormat did its "rollover" calculation and you have an invalid input date.
This was actually a solution given on the checkdate PHP Manual page as a User Contributed Note, though it doesn't involve checkdate itself.

False dateresult using date() php

I want to parse the date 1938 1938+02:00 using date() & strtotime().
My code:
echo date("Y", strtotime("1938+02:00"));
gives me as result "2014"..
What am i doing wrong?
For something like this just get the first four characters of the string. No need to work with dates and such:
echo substr('1938+02:00', 0, 4);
Demo
But if you insist on using date functionality you'll need to use DateTime::createFromFormat() as that date string is not a standard format.
$date = DateTime::createFromFormat('YP', '1938+02:00');
echo $date->format('Y');
Demo
date("Y"); only return the year. That's what the Y does.
See the Manual page for date for other options.
EDIT
Another thing to consider, is that timestamps only go back to 1970. That's what a timestamp is (the number of seconds since 1970).
So, that's going to give you a negative value for the timestamp.
Your date string is not in an acceptable format. here is a list of acceptable formats for strtotime

strtotime() in php returning always 01-01-1970

I am using a variable to get the date from the database,then i am passing that variable to strtotime function to get the desired format,but it always returning wrong date.perhaps there is a problem in passing a variable in strtotime function.please suggest me guys,how should i get the correct date in correct format.
Here is what i am trying to do
$date = $fetch_user['date'];
$newDate = date("d-m-Y", strtotime($date));
$day = date('l', strtotime($newDate));
echo $newDate;
echo "-----";
echo $day;
exit;
January 1, 1970 is the so called Unix epoch. It's the date where they started counting the Unix time. If you get this date as a return value, it usually means that the conversion of your date to the Unix timestamp returned a (near-) zero result. So the date conversion doesn't succeed. Most likely because it receives a wrong input.
In other words, your strtotime($date) returns 0, meaning that $date is passed in an unsupported format for the strtotime function.
So you'll have to check for yourself $date, before calling strtotime at all.
01-01-1970 means you probably get 0 as a result of strtotime(). You are probably using a format, that this function cannot understand. The PHP documentation states:
The function expects to be given a string containing an English date
format and will try to parse that format into a Unix timestamp (the
number of seconds since January 1 1970 00:00:00 UTC), relative to the
timestamp given in now, or the current time if now is not supplied.
So it is not really flexible. You might want to try DateTime::createFromFormat instead. Take a look at it's documentation.
Basically you have to specify the format of the date string, that you give as an input as well. That way you can use whatever date format you want.
Example from php.net:
<?php
$date = DateTime::createFromFormat('j-M-Y', '15-Feb-2009');

PHP convert string with weeks and short month name to date

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.

convert mysql timestamp into php user friendly version

i have 2011-08-03 21:56:41 coming from a MySQL timestamp and I would like to convert it to Wednesday August 3rd, 2011 using PHP (Not MySQL). How can this be done?
Use strtotime() to convert your date/time string to a Unix timestamp so you can use date() to format the value of that timestamp any way you want.
$stamp = '2011-08-03 21:56:41';
echo date('l F jS, Y', strtotime($stamp));
// output: Wednesday August 3rd, 2011
The reference at the date() manual page is extremely useful. I still reference it all the time for the list of special format characters.
The strtotime() function sort of seems like magic at first. For future reference, here's the supported date/time documentation on what input formats strtotime() can accept.

Categories