我怎么知道这是迄今为止在这一年,如果我只知道一天数...在今年变换时至今
比方说,如果我知道那一天是“1”,然后拿到2014年1月1日,如果我知道那天是'32',那么得到01.02.2014?
这是可能的JavaScript?
那么php呢?
我怎么知道这是迄今为止在这一年,如果我只知道一天数...在今年变换时至今
比方说,如果我知道那一天是“1”,然后拿到2014年1月1日,如果我知道那天是'32',那么得到01.02.2014?
这是可能的JavaScript?
那么php呢?
PHP方式:
$first_day_of_this_year = strtotime(date('Y-01-01 00:00:00')); //as unix timestamp
$after_32_days = $first_day_of_this_year + 32 * 24 * 60 * 60;
echo date("Y-m-d", $after_32_days);
这将输出2014-02-02
这将始终本年度工作。如果您想在其他年份使用它,只需在第一个日期()函数中将Y
替换为所需年份。
这应该在闰年时正常工作。
编辑:
我做了一个功能:
function day_number_to_date($day_in_year, $year = null) {
$year = (is_null($year)) ? date("Y") : $year; //use current year if it was not passed to function
$first_day_of_year = strtotime(date("$year-01-01 00:00:00")); //first day of year as unix timestamp
$days_to_add = $day_in_year - 1;
$target_timestamp = $first_day_of_year + $days_to_add * 24 * 60 * 60;
$target_date = date("Y-m-d", $target_timestamp);
return $target_date;
}
echo day_number_to_date(32); //2014-02-01
echo day_number_to_date(32, 2020); //2020-02-01
echo day_number_to_date(400); //2015-02-04
为什么这不为我工作 - 给我错误的日期:$ target_date = date(“l,Ydm”,$ target_timestamp); – 2014-11-02 21:56:27
@JamesD。它为我工作(输出'2014年2月2日星期六'),除了您每月更换一天。 – Lukas 2014-11-03 07:55:11
试试这个:
var date = new Date("" + new Date().getFullYear());
var day = 32;
date.setDate(date.getDate() + day-1);
console.log(date); // => Sat Feb 01 2014 ...
在JavaScript中,你可以通过简单地创建与天参数设置为您所需要一年的一天,一个新Date
对象做到这一点 - 看到MDN参数注意部分:
var dayInYear = 32;
var newDate = new Date(2014, 0, dayInYear);
// newDate is 01 Feb.
,或者如果你有一个现有的Date对象:
var theDate = new Date('01/01/2014');
var dayInYear = 32;
var newDate = new Date(theDate.getFullYear(), theDate.getMonth(), dayInYear);
看完你的问题后,听起来好像你想要提供日期和年份来获取特定的日期。
function getDateFromDay(year, day) {
return new Date((new Date(year, 0)).setDate(day));
}
getDateFromDay(2014, 1); // will give Wed Jan 01 2014 00:00:00
你需要你的代码知道它是什么年代,太 - 每四年讨厌的2月29日 - 但它只是一个连续减去的月份长度,直至剩余物质小于下个月的长度(同时保持跟踪哪个月是最后一次扣除的)。事情是这样的片段(伪C):
day_to_month (year, day_in_year)
{
day_count = day_in_year;
if (not_leap_year());
while (day_in_year < month [month_count])
{
subtract month[month_count++];
}
else
while (day_in_year < leap_month [month_count])
{
subtract leap_month [month_count++];
}
}
date_set (year, month_count, day_count);
我不写javascript,但我知道的任何理由,这可能不会在bash脚本甚至做 - 只是需要声明和初始化能力数组,以及基本的算术和流量控制功能。
function day2Date(day, year) {
return new Date(year,0,day);
}
console.log(day2Date(32, 2014)); //gives Sat Feb 01 2014 00:00:00
这是可能的,支持最新的每一种语言。 – undefined 2014-11-02 11:56:03
一切皆有可能。 但你应该决定,你想要客户端(JavaScript)或服务器端(PHP)的日期处理... 在php中看到mktime()函数... – 2014-11-02 11:56:31