doulan0297 2017-08-16 19:02
浏览 17
已采纳

如何从字符串中获取完整日期而不在PHP中的字符串中包含实际月份?

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?

  • 写回答

4条回答 默认 最新

  • dongshuo2752 2017-08-16 19:20
    关注

    You can do it like this:

    <?php
    $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";
    }
    ?>
    

    Explanation

    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.

    Notes

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(3条)

报告相同问题?

悬赏问题

  • ¥15 程序不包含适用于入口点的静态Main方法
  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 ubuntu子系统密码忘记