如何将JavaScript中的十进制年值转换为Date? [英] How do I convert a decimal year value into a Date in Javascript?
本文介绍了如何将JavaScript中的十进制年值转换为Date?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
好的,这基本上是一个JavaScript版本的如何将十进制年值转换为Ruby中的Date?,而不是 Javascript函数将十进制年值转换为年,月和日
OK, this is basically a Javascript version of How can I convert a decimal year value into a Date in Ruby? and not exactly a duplicate of Javascript function to convert decimal years value into years, months and days
输入:
2015.0596924
2015.0596924
期望的输出:
2015年1月22日
January 22, 2015
我已经解决了(见下文),但我预计(就像这个问题的Ruby版本)有一个更好的方法。
I have solved it (see below), but I expect (just like the Ruby version of this question) that there is a better way.
推荐答案
另一个解决方案是:
- 创建
日期
给定年份(整数部分) - C从提醒(小数部分)计算天数并转换为毫秒
- 将毫秒添加到(1)
- Create
date
for given year (integer part) - Calculate days from reminder (decimal part) and convert to milliseconds
- Add milliseconds to (1)
在脚本中:
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);
您可以在 这个小提琴 。
You can play with it on this Fiddle.
这篇关于如何将JavaScript中的十进制年值转换为Date?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文