jQuery 如何减去两个angularjs日期变量

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15298663/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 14:46:17  来源:igfitidea点击:

How to subtract two angularjs date variables

jqueryangularjs

提问by user1399078

I am fairly new to angularjs, but here it goes. I am able two dates through angularjs in the form dd/mm/yyyy, but what I need to do is somehow subtract the two dates to get the difference in days between the two. I created a jquery function to do this, but I don't know how to pass in the two dates to the function. So I was wondering if there was a different way to go about this?

我对 angularjs 还很陌生,但它就在这里。我可以通过 angularjs 形式的两个日期dd/mm/yyyy,但我需要做的是以某种方式减去这两个日期以获得两者之间的天数差。我创建了一个 jquery 函数来执行此操作,但我不知道如何将两个日期传递给该函数。所以我想知道是否有不同的方法来解决这个问题?

I am trying to set up a trigger system depending on the number of days in between the two dates for certain things to be stylized. For example if it's within 10 days I want it to use style 1and if its within 20 days use style 2and so on.

我正在尝试根据两个日期之间的天数来设置一个触发系统,以便将某些事物风格化。例如,如果是在 10 天内,我希望它使用样式 1,如果它在 20 天内使用样式 2,依此类推。

采纳答案by Chris Moutray

I'm also an angularjs novice but wouldn't you handle this by making properties available through your javascript view model?

我也是一个 angularjs 新手,但您不会通过通过您的 javascript 视图模型提供属性来处理这个问题吗?

For example have a stylefield that changes based on the date fields (ie style returns style 1 when if the difference is 10 days) and hopefully through the angularjs binding the updates will propagate to the screen.

例如,有一个根据日期字段更改的样式字段(即,如果差异为 10 天,则样式返回样式 1),并且希望通过 angularjs 绑定将更新传播到屏幕。

I think the right term for this is a computed propertyor calculated property

我认为正确的术语是计算属性计算属性

EDIT

编辑

Not sure if this is what you're looking for but see fiddle for example of calculating date diff and changing a style all based off properties of the view model (scope)

不确定这是否是您要查找的内容,但请参阅 fiddle 例如计算日期差异和更改样式的所有基于视图模型(范围)的属性

scope.diffand scope.colare the 2 properties to bind to

scope.diff并且scope.col是结合到2个属性

http://jsfiddle.net/chrismoutray/wfjv6/

http://jsfiddle.net/chrissoutray/wfjv6/

HTML

HTML

<script src="http://code.angularjs.org/0.10.4/angular-0.10.4.min.js" ng:autobind></script>
<div ng:controller="ComputedPropertiesCtrl">
    first date <input ng:model="firstdate"> second date <input ng:model="seconddate"> difference {{diff}}
    <div>when the difference is greater than 10 color changes to green</div>
    <div>eg set the second date to 15/01/2013</div>
    <div style="background-color:{{col}};"> State </div>
</div>

JS

JS

function ComputedPropertiesCtrl() {
    var scope = this;
    scope.firstdate = '01/01/2013';
    scope.seconddate = '10/01/2013';
    scope.data_before = [];
    scope.differenceInDays = function() {

        var dt1 = scope.firstdate.split('/'),
            dt2 = scope.seconddate.split('/'),
            one = new Date(dt1[2], dt1[1]-1, dt1[0]),
            two = new Date(dt2[2], dt2[1]-1, dt2[0]);

        var millisecondsPerDay = 1000 * 60 * 60 * 24;
        var millisBetween = two.getTime() - one.getTime();
        var days = millisBetween / millisecondsPerDay;

        return Math.floor(days);      
    };
    scope.color = function() {
        return (scope.differenceInDays() > 10) ? 'green' : 'red';
    };

    scope.$watch('[firstdate, seconddate]', function(currScope,newVal,oldVal) {
        scope.data_before = oldVal;
        scope.diff = scope.differenceInDays();
    });

    scope.$watch('[firstdate, seconddate]', function(currScope,newVal,oldVal) {
        scope.data_before = oldVal;
        scope.col = scope.color();
    });
}

CSS

CSS

h2 { position: fixed; right: 10px; top: 10px; color: red; background:white;z-index:1000; }
input { width: 100px; }
div { margin: 10px; padding: 10px; }

回答by Stewie

Basic javascript way:

基本的javascript方式:

var d1 = new Date('01/16/2013');
var d2 = new Date('02/26/2013');
var milliseconds = d2-d1;
var seconds = milliseconds / 1000;
var minutes = seconds / 60;
var hours = minutes / 60;
var days = hours / 24;

Using one of the Date libraries (such as moment.js):

使用 Date 库之一(例如 moment.js):

var d1 = moment("01/16/2013");
var d2 = moment("02/26/2013");
var days = moment.duration(d2.diff(d1)).asDays();

回答by Pawan Singh

you simply convert date into timestamp and then subtract.

您只需将日期转换为时间戳,然后减去。

var Date1 = 08/16/2004;
var Date2= 10/24/2005;

var timestamp1 = new Date(Date1).getTime();
var timestamp2 = new Date(Date2).getTime();

var diff = timestamp1 - timestamp2


var newDate = new Date (diff);

回答by s1moner3d

You can use angular-momentto calculate the difference, using the amDifferencefilter:

您可以使用angular-moment来计算差异,使用amDifference过滤器:

Get the difference between two dates in milliseconds. Parameters are date, units and usePrecision. Date defaults to current date. Example:

以毫秒为单位获取两个日期之间的差异。参数是日期、单位和 usePrecision。日期默认为当前日期。例子:

<span>Difference: {{ dateFrom | amDifference : dateTo : 'days' }} days</span>

回答by Nick Steele

This works, and here are 2 flawless javascript date functions you should never be without...

这是有效的,这里有 2 个完美的 javascript 日期函数,你永远不应该没有......

// Returns the days between a & b date objects...
function dateDiffInDays(a, b) {
    var _MS_PER_DAY = 1000 * 60 * 60 * 24;
    // Discard the time and time-zone information.
    var utc1 = Date.UTC(a.getFullYear(), a.getMonth(), a.getDate());
    var utc2 = Date.UTC(b.getFullYear(), b.getMonth(), b.getDate());
    return Math.floor((utc2 - utc1) / _MS_PER_DAY);
}

// Calculate how many days between now and an event...
function daysTill(e) {
    var eventE = new Date(e);
    var today =  new Date();
    return dateDiffInDays(today, eventE);
}

回答by Rohit Luthra



The moment JavaScript library is really very useful and easy to use:

JavaScript 库真的非常有用且易于使用:



var parsedServerOutTime = moment(serverOutTime, "HH:mm:ss");
var parsedServerInTime = moment(serverInTime, "HH:mm:ss");

var milliseconds= parsedServerOutTime.diff(parsedServerInTime) //default milliseconds
var days = moment.duration(parsedServerOutTime .diff(parsedServerInTime )).asDays();// For days

asWeeks();asMonths();asYears();etc etc for more details check http://momentjs.com/docs/

asWeeks();asMonths();asYears();等更多详情请查看http://momentjs.com/docs/

回答by Abc

I tried the below one and it worked out for me

我尝试了下面的一个,它对我有用

var selecteddate = new Date($rootscope.selectvalue);
$scope.firstDate = selecteddate .getTime();
$scope.SecondDate = new Date().getTime();

selected date is the one which is selected from calender and it is coming from parent scope. second date will be today's date. later i will find difference using moment diff.

selected date 是从日历中选择的日期,它来自父范围。第二个日期将是今天的日期。稍后我将使用 moment diff 发现差异。

var differenceinDays=parseInt(
      moment.duration(
        moment($scope.firstDate).diff(
          moment($scope.SecondDate)
        )
      ).asDays()
    );

I am using parseInt because i want to return the integer value only

我使用 parseInt 因为我只想返回整数值

Hope this works

希望这有效