admin管理员组

文章数量:1287858

I'm using AngularJS for my application and the date object is $scope.ProductionDate.

From 5:00AM 2017-02-21 (Feb 21st) to 4:59AM 2017-02-22 (Feb 22nd)

I want the ProductionDate value to be 2017-02-21.

P.S. Here Feb 21st is just an example. Daily I want the same value in given timings.

Can I know how to get that?

function Ctrl($scope)
{
    $scope.ProductionDate = new Date();
}
<script src=".2.23/angular.min.js"></script>
<div ng-app ng-controller="Ctrl">
    ProductionDate: {{ProductionDate | date:'yyyy-MM-dd'}}<br/> 
</div>

I'm using AngularJS for my application and the date object is $scope.ProductionDate.

From 5:00AM 2017-02-21 (Feb 21st) to 4:59AM 2017-02-22 (Feb 22nd)

I want the ProductionDate value to be 2017-02-21.

P.S. Here Feb 21st is just an example. Daily I want the same value in given timings.

Can I know how to get that?

function Ctrl($scope)
{
    $scope.ProductionDate = new Date();
}
<script src="https://ajax.googleapis./ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app ng-controller="Ctrl">
    ProductionDate: {{ProductionDate | date:'yyyy-MM-dd'}}<br/> 
</div>

Share Improve this question asked Feb 21, 2017 at 19:58 RangerRanger 1293 silver badges11 bronze badges 3
  • What do you want to happen with Production date? – Deividas Commented Feb 21, 2017 at 20:05
  • I mean from today morning 5:00AM to tommorow morning 4:59AM I want the date to be today's date – Ranger Commented Feb 21, 2017 at 20:06
  • Moment.js (momentjs.) is worth a look here. There my be JS or even Angular ways to do it, but nothing is quite as simple as using moment.js when it es to calculations and formatting of dates, especially if you are likely to have other needs for it in your project. – Paul Thomas Commented Feb 21, 2017 at 20:16
Add a ment  | 

3 Answers 3

Reset to default 8

You can subtract minutes and hours in javascript from the Date() object.

function Ctrl($scope)
{
    var now = new Date();
    now.setHours(now.getHours()-4);
    now.setMinutes(now.getMinutes()-59);
    $scope.ProductionDate = now;
}

It seems that you want to subtract 5 hours, so that the earlier date is shown. Here is a SO post which explains how to modify Date object: Adding hours to Javascript Date object? (nevermind the title - you can use the same principles to subtract the hours).

This same operation may also be done by setting the desired timezone.

Just check if date hours are between 0 and 5 or not

function Ctrl($scope)
{
    var now = new Date();
    if(now.getHours() < 5 && now.getHours() >= 0){
        // Subtract one day
        now.setDate(now.getDate() - 1);
    }
    $scope.ProductionDate = now;
}

本文标签: javascriptHow to subtract some Hours from current Time in AngularJSStack Overflow