计算日期与开始日期和数量的JavaScript天 [英] Calculate Date with start date and number of days with javascript

查看:147
本文介绍了计算日期与开始日期和数量的JavaScript天的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图来计算起始日期和天数的日期,所以basicly天数添加到开始日期,并得到一个结束日期。问题是我得到一些奇怪的结果,但只能在一个日期,我已经几天,现在试图找出这一个。

I am trying to calculate a date from a start date and number of days, so basicly add the number of days to a start date and get an end date. The issue is I get some strange results, but only on one date, I have been a few days now trying to figure this one out.

的功能是:

CallculateDateFromDays = function(startDate, days) {
var policy_start_date_array = startDate.split("-");
var policy_start_date = new Date(policy_start_date_array[2], policy_start_date_array[1]-1, policy_start_date_array[0]);
var policy_start_date_add = new Date(policy_start_date.getTime() + ((days-1) * 24 * 60 * 60 * 1000));
var dateString = ("0" + (policy_start_date_add.getDate())).slice(-2) + "-" + ("0" + (policy_start_date_add.getMonth()+1)).slice(-2) + "-" + policy_start_date_add.getFullYear();
return dateString;}

关键是它的工作,直到我使用日期28-10-2012它给我回相同的日期,即使我加2天。

The thing is it works until I use the date "28-10-2012" it gives me back the same date even if I add 2 days.

任何想法,我很为难。

推荐答案

的夏令时结束的,因为有可能是你的本地时区的变化。

Likely your local timezone changes because of the end of the daylight saving time.

> new Date(2012, 9, 28)
Sun Oct 28 2012 00:00:00 GMT+0200
> // 48 hours later:
> new Date(new Date(2012, 9, 28) + 2 * 24 * 60 * 60 * 1000)
Mon Oct 29 2012 23:00:00 GMT+0100

始终使用UTC方法!

Always use the UTC methods!

顺便说一句,加入天与的setDate ,这也能解决时区的问题更容易:

BTW, adding days is much more easier with setDate, which also works around timezone issues:

function calculateDateFromDays(startDate, days) {
    var datestrings = startDate.split("-"),
        date = new Date(+datestrings[2], datestrings[1]-1, +datestrings[0]);
    date.setDate(date.getDate() + days);
    return [("0" + date.getDate()).slice(-2), ("0" + (date.getMonth()+1)).slice(-2), date.getFullYear()].join("-");
}

这篇关于计算日期与开始日期和数量的JavaScript天的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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