nats nats - 6 months ago 47
PHP Question

PHP Get full date from string without having the actual month in the string

Is there any way to get the full date from a string that does not actually contain the month?

i am given the date in a format of

Wednesday 16th
and need to add this to my database with a month,

The application i am making is for lifestyle couriers and they get their manifests in that format and have the last 2 months available, so i need to find out the month?

Answer Source

You can do it like this:

$date = 16;
$day = "Wednesday";

$oneMonthAgo = explode(" ",date("m Y F",strtotime("-1 month")));
$twoMonthsAgo = explode(" ",date("m Y F",strtotime("-2 months")));

if (date("l",strtotime($date."-".$oneMonthAgo[0]."-".$oneMonthAgo[1]))==$day) {
    echo "Last month: ".$oneMonthAgo[2];
else if (date("l",strtotime($date."-".$twoMonthsAgo[0]."-".$twoMonthsAgo[1]))==$day) {
    echo "Month before last: ".$twoMonthsAgo[2];
else {
    echo "Not valid";


Because you are using PHP, there is an easy way to do this. In other languages, you would have to use a weekday algorithm.

In PHP, we can convert a properly formatted string into a time, from which we can then derive date information. Examples of a properly formatted string is -1 month or -2 months, which return time objects for the previous month or the month before that, respectively.

Using the date() function, we can get the month, year and textual month values for those months. We delimiter these by a space, so that we can explode these values into an array after they are found. Thus, we now have two arrays, $oneMonthAgo and $twoMonthsAgo, which both contain their month's respective number, year and textual month at the 0, 1 and 2 indexes respectively.

Now, we can create another time, by appending the date that we are looking for ($date) onto these values, with the proper delimiters in-between (when using - as the delimiters, PHP assumes a d-m-Y format, when using / PHP assumes a m-d-Y format). Then, by passing that through another date() function, we can find the data that we are looking for: the textual day that took place at that date. Now we can simply compare that to the day that we are looking for, $day. If the textual day is the same, then this is the month which we are looking for, so we can print out the full textual month.

We do this in an if / else statement for both months, and if we still haven't found it, assume that the date is invalid.


Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download