将一年中的某一天转换为当前日期


Transform day in year to date

如果我只知道日期是数字,我如何找到今年的日期。。。

比方说,如果我知道那一天是"1",那么就可以得到2014年1月1日;如果我知道那天是"32",那么就会得到2014年2月1日?

这在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

这将永远适用于今年。如果您想在其他年份使用它,只需将firstdate()函数中的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

在JavaScript中,只需创建一个新的Date对象,将days参数设置为所需的一年中的某一天,即可实现这一点-请参阅MDN:上的Parameters注释部分

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

试试这个:

var date = new Date("" + new Date().getFullYear() );
var day = 32;
date.setDate(date.getDate() + day-1);
console.log(date); // => Sat Feb 01 2014 ...

function day2Date( day, year ) {
  return new Date(year,0,day);
}
console.log( day2Date( 32, 2014 ) ); //gives Sat Feb 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脚本中也不能做到这一点——只需要声明和初始化数组的能力,以及基本的算术和流控制函数。