如何在Javascript中将十进制年份值转换为日期?

时间:2015-04-01 20:30:45

标签: javascript date

好的,这基本上是How can I convert a decimal year value into a Date in Ruby?的Javascript版本而不是完全Javascript function to convert decimal years value into years, months and days的副本

输入:

  

2015.0596924

期望的输出:

  

2015年1月22日

我已经解决了(见下文),但我希望(就像这个问题的Ruby版本一样)有更好的方法。

3 个答案:

答案 0 :(得分:2)

如果您添加太多时间,JavaScript将为您解析日期。见下面的演示。下面的解决方案不会根据算法计算闰年,而是采用明年的日期并从今年开始减去它。这假设JavaScript规范正确计算闰年。

有关详细信息,请参阅Mozilla Docs

function decimalDateToJsDate(time) {
  var year = Math.floor(time);
  var thisYear = new Date(year, 0, 1);
  var nextYear = new Date(year + 1, 0, 1);
  var millisecondsInYear = nextYear.getTime() - thisYear.getTime();
  var deltaTime = Math.ceil((time - year) * millisecondsInYear);
  thisYear.setMilliseconds(deltaTime);
  return thisYear;
}

document.getElementById("output").innerHTML = decimalDateToJsDate(2015.0596924);
<pre id="output"></pre>

答案 1 :(得分:2)

另一个解决方案是:

  1. 为给定年份(整数部分)创建date
  2. 从提醒计算天数(小数部分)并转换为毫秒
  3. 将毫秒添加到(1)
  4. 在剧本中:

    function leapYear(year) {
        return ((year % 4 == 0) && (year % 100 != 0)) || (year % 400 == 0);
    };
    
    function convertDecimalDate(decimalDate) {
        var year = parseInt(decimalDate);
        var reminder = decimalDate - year;
        var daysPerYear = leapYear(year) ? 366 : 365;
        var miliseconds = reminder * daysPerYear * 24 * 60 * 60 * 1000;
        var yearDate = new Date(year, 0, 1);
        return new Date(yearDate.getTime() + miliseconds);
    }
    
    var date = convertDecimalDate(2015.0596924);
    console.log(date);

    您可以在 this Fiddle 上播放。

答案 2 :(得分:1)

function leapYear (year){
  return ((year % 4 == 0) && (year % 100 != 0)) || (year % 400 == 0);
}

function getMonthAndDayFromDayOfYear(dayOfYear, year){
  var daysInMonthArray = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
  if (leapYear(year)) { daysInMonthArray[2] = 29; }

  var daysLeft = dayOfYear;
  var month = 0;
  for (i=0; i<daysInMonthArray.length; i++) {
    var daysInThisMonth = daysInMonthArray[i];
    if (daysLeft > daysInThisMonth) {
      month += 1;
      daysLeft -= daysInThisMonth;
    } else {
      break;
    }
  }
  return { month: month, day: daysLeft };
}

function convertDecimalDate(decimalDate){
  decimalDate = parseFloat(decimalDate);
  var year = parseInt(decimalDate); // Get just the integer part for the year
  var daysPerYear = leapYear(year) ? 366 : 365; // Set days per year based on leap year or not
  var decimalYear = decimalDate - year; // A decimal representing portion of the year left
  var dayOfYear = Math.ceil(decimalYear * daysPerYear); // day of Year: 1 to 355 (or 366)
  var md = getMonthAndDayFromDayOfYear(dayOfYear, year);
  var day = md['day'];
  var month = md['month'];
  return new Date(year,month,day);
}

var date = convertDecimalDate(2015.0596924);