如何用JavaScript确定从现在开始的一年 [英] How to determine one year from now in Javascript

查看:69
本文介绍了如何用JavaScript确定从现在开始的一年的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想从现在起算是一年,但它不起作用.

I'm trying to get one year from now's date, and it's not working.

JS:

var now = new Date();

var oneYr = new Date();
oneYr.setYear(now.getYear() + 1);
$("#yearFromNow").append(oneYr.toString());

var oneMonth = new Date();
oneMonth.setMonth(now.getMonth() + 1);
$("#monthFromNow").append(oneMonth.toString());

输出:

one mo. = Thu Dec 22 112 15:16:01 GMT-0500 (Eastern Standard Time)

one yr. = Sun Jan 22 2012 15:16:01 GMT-0500 (Eastern Standard Time)

年份为 Dec 22112 -??该月正确显示了 2012年1月22日.

The year has Dec 22 112 - ?? The month is correctly displaying Jan 22 2012.

如果您想修改它,请 http://jsbin.com/alezaj/edit#javascript,html,live .这是在Chrome和Firefox中.

If you want to tinker with it, http://jsbin.com/alezaj/edit#javascript,html,live. This is in Chrome and Firefox.

谢谢!

推荐答案

您应该使用 getFullYear()而不是 getYear(). getYear()返回的实际年份减去1900(因此毫无用处).

You should use getFullYear() instead of getYear(). getYear() returns the actual year minus 1900 (and so is fairly useless).

因此,从当前时刻算起恰好是一年的日期将是:

Thus a date marking exactly one year from the present moment would be:

var oneYearFromNow = new Date();
oneYearFromNow.setFullYear(oneYearFromNow.getFullYear() + 1);

请注意,如果您将日期设置为2月29日,则会对此日期进行调整.

Note that the date will be adjusted if you do that on February 29.

类似地,您可以通过 getMonth() setMonth()获得距现在一个月的日期.如果您在12月这样做,则不必担心从当前年度过渡"到明年.日期将自动调整.每月的同一天通过 getDate() setDate().

Similarly, you can get a date that's a month from now via getMonth() and setMonth(). You don't have to worry about "rolling over" from the current year into the next year if you do it in December; the date will be adjusted automatically. Same goes for day-of-month via getDate() and setDate().

这篇关于如何用JavaScript确定从现在开始的一年的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆