从数字索引获取[NTH] [DAYNAME] [月]的日期而不转换为字符串?

时间:2016-01-08 04:40:12

标签: php date datetime

假设您有四个数字变量:

$Index=2; // 1-6, 2 is the second occurrence
$Dow=3; // 0-6, 3 is Wednesday
$Month=3; // 1-12, 3 is March
$Year=2016;

是否有一种简单的方法可以使用数字来创建或修改DateTime对象来表示该特定日期?例如,对于上述变量,它将是2016年3月第二个星期三的具体日期。

我知道您可以使用strtotimeDateTime构造函数执行此操作,如果您已将其写为字符串。这里有其他答案可以处理。

但是因为我们有数字索引,所以创建一个将数字转换为人类可读字符串然后传递给字符串解析器以生成日期的函数似乎很愚蠢。

所以问题是,是否有一种方法可以使用严格数字变量与DateTime对象,而必须先将其转换为人类可读的字符串得到一个相对日期,如3月(3)的星期三(3)第二(2)?

我正在寻找类似的东西:

$oDate = new DateTime();
$oDate->setFromWeekdayOfMonthIndex($Position,$DOWNum,$MonthNum,$Year);

更新#1

只是为了澄清这个问题,这就是我想要的,但这是一个漫长/愚蠢的方式:

$oMonthDate = new DateTime();
$oMonthDate->setDate($Year, $MonthNum, 1);

$oFormater = new NumberFormatter('en-US', NumberFormatter::SPELLOUT);
$oFormater->setTextAttribute(NumberFormatter::DEFAULT_RULESET,"%spellout-ordinal");

$String  = $oFormater->format($Position).' ';
$String .= date('l', strtotime('Sunday +'.$DOW.' days')). ' of ';            
$String .= $oMonthDate->format('F'). ' '.$Year;

$oFinalDate = new DateTime($String); // "second Tuesday of January 2016"

0 个答案:

没有答案