douye1876 2013-04-16 22:45
浏览 18
已采纳

php日期格式化帮助日期格式即使与文档匹配也不提供有效日期

read and have re read the documentation and truly cannot explain why $date1 comes through bad

can someone help? Greatly appreciate it

$date1 = "04-16-2013";
$date2 = "2013-04-16";
printf("date1 = %s
", $date1);
printf("date2 = %s
", $date2);

$newdate1 = date('m-d-Y',$date1);
$newdate2 = date('Y-m-d',$date2);
printf("newdate1 = %s
", $newdate1);
printf("newdate2 = %s
", $newdate2);

$previous_date = date('m-d-Y', strtotime($date1 .' -1 day'));
$previous_date2 = date('m-d-Y', strtotime($date2 .' -1 day'));
printf("previous_date = %s
", $previous_date);
printf("previous_date2 = %s
", $previous_date2);

OUTPUT

 date1 = 04-16-2013
    date2 = 2013-04-16
    newdate1 = 12-31-1969
    newdate2 = 1969-12-31
    previous_date = 12-31-1969
    previous_date2 = 04-15-2013
  • 写回答

2条回答 默认 最新

  • dqrdlqpo775594 2013-04-16 23:14
    关注

    strtotime function

    Dates in the m/d/y or d-m-y formats are disambiguated by looking at the separator between the various components: if the separator is a slash (/), then the American m/d/y is assumed; whereas if the separator is a dash (-) or a dot (.), then the European d-m-y format is assumed.

    To avoid potential ambiguity, it's best to use ISO 8601 (YYYY-MM-DD) dates or DateTime::createFromFormat() when possible.

    In your case because you are using the separator dash (-) php consider that the date format is in d-m-y.

    Or a workaround:

    $date1 = "04-16-2013";
    $date2 = "2013-04-16";
    printf("date1 = %s
    ", $date1);
    printf("date2 = %s
    ", $date2);
    
    
    $newdate1 = date('m-d-Y',strtotime(str_replace("-","/",$date1)));
    $newdate2 = date('Y-m-d', strtotime($date2));
    printf("newdate1 = %s
    ", $newdate1);
    printf("newdate2 = %s
    ", $newdate2);
    
    
    $previous_date = date('m-d-Y', strtotime(str_replace("-","/",$date1) .' -1 day'));
    $previous_date2 = date('m-d-Y', strtotime($date2 .' -1 day'));
    printf("previous_date = %s
    ", $previous_date);
    printf("previous_date2 = %s
    ", $previous_date2);
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 求lingo代码和思路
  • ¥15 公交车和无人机协同运输
  • ¥15 stm32代码移植没反应
  • ¥15 matlab基于pde算法图像修复,为什么只能对示例图像有效
  • ¥100 连续两帧图像高速减法
  • ¥15 如何绘制动力学系统的相图
  • ¥15 对接wps接口实现获取元数据
  • ¥20 给自己本科IT专业毕业的妹m找个实习工作
  • ¥15 用友U8:向一个无法连接的网络尝试了一个套接字操作,如何解决?
  • ¥30 我的代码按理说完成了模型的搭建、训练、验证测试等工作(标签-网络|关键词-变化检测)