如何将年份字符串转换为PHP中的日期?

如何将年份字符串转换为PHP中的日期?

问题描述:

I am trying to convert a string into a date. Specifically, a string of a year into a date.

strtotime('2017') // Gives us -> 1517372220

$year = '2017';
var_dump($year); // '2017'
$year = date("Y", strtotime($year));
var_dump($year); // '2018' 

Why is the date method defaulting to the current time? I am passing an integer.

According to the documentation, I seem to implementing this method correctly?

string date ( string $format [, int $timestamp = time() ] )

The optional timestamp parameter is an integer Unix timestamp that defaults to the current local time if a timestamp is not given. In other words, it defaults to the value of time().

我正在尝试将字符串转换为日期。 具体来说,是一年中的一串日期。 p>

  strtotime('2017')//给我们 - >  1517372220 
 
 $ year ='2017'; 
var_dump($ year);  //'2017'
 $ year = date(“Y”,strtotime($ year)); 
var_dump($ year);  //'2018'
  code>  pre> 
 
 

为什么日期方法默认为当前时间? 我传递一个整数。 p>

根据文档,我似乎正确地实现了这个方法? p>

字符串日期(字符串$ format [,int $ timestamp = time()]) p>

可选的timestamp参数是 整数Unix时间戳,如果没有给出时间戳,则默认为当前本地时间。 换句话说,它默认为time()的值。 p> blockquote> div>

Based on strtotime() Manual

strtotime — Parse about any English textual datetime description into a Unix timestamp

Parameters

time-> A date/time string. Valid formats are explained in Date and Time Formats.

So either you need to provide a textual representation or a valid date format (not only years).

So code need to be like this:-

<?php

$year = date("Y", strtotime('2017-01-01'));
var_dump($year); // '2018' 

Output:- https://eval.in/945561

Reference:- valid formats for strtotime()