2

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.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app ng-controller="Ctrl">
    ProductionDate: {{ProductionDate | date:'yyyy-MM-dd'}}<br/> 
</div>
Ranger
  • 129
  • 2
  • 11
  • What do you want to happen with Production date? – Deividas Feb 21 '17 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 Feb 21 '17 at 20:06
  • Moment.js (https://momentjs.com/) 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 comes to calculations and formatting of dates, especially if you are likely to have other needs for it in your project. – Paul Thomas Feb 21 '17 at 20:16

3 Answers3

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;
}
Stephan
  • 666
  • 8
  • 23
  • I'm not asking that. from today morning 5:00AM to tomorrow morning 4:59AM I want the date to be today's date – Ranger Feb 21 '17 at 20:06
  • @Ranger I've updated to match your comment. You may need to drop the minutes line and just subtract 5 hours. you can test to see which works, and let me know. I'm not somewhere where i can test it to confirm. – Stephan Feb 21 '17 at 20:14
1

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.

Community
  • 1
  • 1
Deividas
  • 6,437
  • 2
  • 26
  • 27
  • The timezone mention is especially astute. For other readers, Deividas is assuming the reason for the odd hours is because the app is intended for users in another region than the server. – Stephan Feb 21 '17 at 21:50
1

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;
}
Mhd
  • 2,778
  • 5
  • 22
  • 59