PHP的上个月和当年输出

时间:2018-10-29 19:50:03

标签: php

从PHP开始,我试图输出最后一个月并给出该月的年份,但是输出太混乱了,可能是因为我是新手。

代码:

<?php 
$lastmonth = mktime(0, 0, 0, date("m")-1, date("Y")); 
echo($lastmonth);

输出:

1710028800

2 个答案:

答案 0 :(得分:1)

您可以使用日期时间对象或strtotime(),然后使用date()DateTime::format()对其进行格式化。 DateTime对象或strtotime()都可以采用字符串值,例如“ 上个月”或“ 上周一”,并使用它们创建时间戳/ DateTime对象日期。

使用“ 上个月”时,对应的时间是一个月前,因此,在2018年10月29日20:58时运行此代码,将导致日期时间对象/时间戳记为2018年9月29日20:58。

  • 使用strtotime()

    echo date("Y", strtotime("last month"));
    
  • 使用DateTime对象

    $date = new DateTime("last month");
    echo $date->format("Y");
    

两者都将输出2018,因为此答案的最后一个月是2018年9月。

请参阅此live demo

修改
如果要使用自己的名称而不是月份,请获取月份的数值(1-12),然后使用数组。如果不对数组进行索引,而让PHP处理,则它将从0开始,而不是1-因此应减去1。请注意,如果您尝试用自己的语言来使用月份,请查看strftime()而不是date(),并完全避免使用数组。

$names = array("First - January", "Second - February", "Third - March", "Fourth", "Fifth", "Sixth", "Seventh", "Eight", "Ninth", "Tenth", "Eleventh", "Twelfth");
$month = date("n", strtotime("last month"));

echo $names[$month-1];

答案 1 :(得分:0)

那呢? :)

$socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
if ($socket === false) {
    die("socket_create() failed: reason: " . socket_strerror(socket_last_error()));
}
$result = socket_connect($socket, $address, 80);
if ($result === false) {
    die("socket_connect() failed.\nReason: ($result) " . socket_strerror(socket_last_error($socket)));
}
$out=implode("\r\n",array("GET ".substr($url,strpos($url,"/"))." http/1.0","User-Agent: foobar","","");
socket_send($socket,$out,strlen($out),0);
$last='';
$total='';
while(!!socket_recv($socket,$last,2048,MSG_WAITALL)){
    $total.=$last;
    $last='';
}
socket_close($socket);
$image_binary=substr($total,strpos($total,"\r\n\r\n"));
相关问题