Setting the Date in Angular.js: A Step-by-Step Guide

Make maxDate selectable as today at the latest (past days are clickable but not tomorrow). The range between minDay and maxDay should not exceed 365 days, allowing for fewer days to be selected.

$scope.dateOptions = {
                    formatYear: "yy",
                    minDate: getMinDate(),
                    maxDate: new Date(),
                    startingDay: 1
                };

                function getMinDate() {
                    var oldDay = new Date();
                    oldDay.setDate(oldDay.getDate() -  365);
                    return oldDay;
                };

This restriction is insufficient. I want to set maxDate as 1/03/2021, which should then allow selecting dates from 365 days ago up to 1/04/2020.

Additionally, a validation rule needs to be implemented where minDate cannot be later than maxDate.

Below is the relevant portion of HTML code:

<div class="row">
                <div class="col-sm-3">
                    <label for="sel1">{{ 'LISTLOG_SEARCHSTARTDATE' | translate }}:
                        <!--             <a class="ion-information-circled" tooltip-animation="true" tooltip-placement="top"  -->
                        <!--                uib-tooltip="{{'TOOLTIP_DEVICELOG_SEARCHDATE' | translate}}"></a> -->
                    </label>
                    <p class="input-group">
                        <input type="text" class="form-control" uib-datepicker-popup="{{format}}" ng-model="logVariables.startDate"
                            ng-change="formatDateModal()" ng-model-options="{timezone: 'UTC'}" is-open="popup1.opened"
                            datepicker-options="dateOptions" close-text="Close" alt-input-formats="altInputFormats" />
                        <span class="input-group-btn">
                            <button type="button" class="btn btn-default" ng-click="open1()"><i
                                    class="glyphicon glyphicon-calendar"></i></button>
                        </span>
                    </p>
                </div>
                <div class="col-sm-3">
                    <label for="sel1">{{ 'LISTLOG_SEARCHENDDATE' | translate }}:
                        <!--             <a class="ion-information-circled" tooltip-animation="true" tooltip-placement="top"  -->
                        <!--                uib-tooltip="{{'TOOLTIP_DEVICELOG_SEARCHDATE' | translate}}"></a> -->
                    </label>
                    <p class="input-group">
                        <input type="text" class="form-control" uib-datepicker-popup="{{format}}" ng-model="logVariables.endDate"
                            ng-change="formatDateModal()" ng-model-options="{timezone: 'UTC'}" is-open="popup2.opened"
                            datepicker-options="dateOptions" close-text="Close" alt-input-formats="altInputFormats" />
                        <span class="input-group-btn">
                            <button type="button" class="btn btn-default" ng-click="open2()"><i
                                    class="glyphicon glyphicon-calendar"></i></button>
                        </span>
                    </p>
                </div>

            </div>

Answer №1

Make sure to pass references in your object. I updated the name of the mindate function for clarity

function calculateStartDateFromEndDate(date) { //pass in the relative end date reference
    var oldDay = new Date(date);
    oldDay.setDate(oldDay.getDate() - 365);
    return getUTCDate(oldDay);
};

let endDate = getUTCDate(new Date('2021-01-03')); // arbitrary end date setting
let startDate = calculateStartDateFromEndDate(endDate)

$scope.logVariables = {
    startDate: startDate,
    endDate: endDate
}

$scope.dateOptions = {
    formatYear: "yyyy",
    minDate: startDate,
    maxDate: endDate,
    startingDay: 1
};

To account for UTC time usage, here's a snippet that demonstrates how to convert to UTC and set up min/max dates using UTC

function getUTCDate(date) {
   var now_utc = Date.UTC(date.getUTCFullYear(), date.getUTCMonth(), date.getUTCDate(), date.getUTCHours(), date.getUTCMinutes(), date.getUTCSeconds());
   return new Date(now_utc);
}

angular.module('dateExample', ['ngSanitize', 'ui.bootstrap'])
  .controller('ExampleController', ['$scope', function($scope) {

    function getUTCDate(date) {
      var now_utc = Date.UTC(date.getUTCFullYear(), date.getUTCMonth(), date.getUTCDate(),
        date.getUTCHours(), date.getUTCMinutes(), date.getUTCSeconds());
      return new Date(now_utc);
    }

    function calculateStartDateFromEndDate(date) {
      var oldDay = new Date(date);
      oldDay.setDate(oldDay.getDate() - 365);
      return getUTCDate(oldDay);
    };

    $scope.popup1 = {
      opened: false
    };
    $scope.popup2 = {
      opened: false
    };
    $scope.open1 = function() {
      $scope.popup1.opened = true;
    };

    $scope.open2 = function() {
      $scope.popup2.opened = true;
    };

    let endDate = getUTCDate(new Date('2021-01-03'));
    let startDate = calculateStartDateFromEndDate(endDate)
    $scope.logVariables = {
      startDate: startDate,
      endDate: endDate
    }
    $scope.format = 'dd-MM-yyyy';
    $scope.altInputFormats = ['M!/d!/yyyy'];


    $scope.dateOptions = {
      formatYear: "yyyy",
      minDate: startDate,
      maxDate: endDate,
      startingDay: 1
    };


    $scope.formatDateModal = function() {
      console.log($scope.logVariables)
    }


  }]);
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.6.1/angular.js"></script>
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.6.1/angular-animate.js"></script>
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.6.1/angular-sanitize.js"></script>
<script src="//angular-ui.github.io/bootstrap/ui-bootstrap-tpls-2.5.0.js"></script>
<link href="//netdna.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet">
<div ng-app="dateExample">
  <div ng-controller="ExampleController">
    <div class="row">
      <div class="col-sm-3 col-md-3">
        <label for="sel1">Label 1</label>
        <p class="input-group">
          <input type="text" class="form-control" uib-datepicker-popup="{{format}}" ng-model="logVariables.startDate" ng-change="formatDateModal()" ng-model-options="{timezone: 'UTC'}" is-open="popup1.opened" datepicker-options="dateOptions" close-text="Close"
            alt-input-formats="altInputFormats" />
          <span class="input-group-btn">
<button type="button" class="btn btn-default" ng-click="open1()">
<i class="glyphicon glyphicon-calendar"></i></button>
</span>
        </p>
      </div>
      <div class="col-sm-3 col-md-3">
        <label for="sel1">Label 2</label>
        <p class="input-group">
          <input type="text" class="form-control" uib-datepicker-popup="{{format}}" ng-model="logVariables.endDate" ng-change="formatDateModal()" ng-model-options="{timezone: 'UTC'}" is-open="popup2.opened" datepicker-options="dateOptions" close-text="Close" alt-input-formats="altInputFormats"
          />
          <span class="input-group-btn">
<button type="button" class="btn btn-default" ng-click="open2()">
 <i class="glyphicon glyphicon-calendar"></i>
</button>
 </span>
        </p>
      </div>
    </div>
  </div>
</div>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Does minifying Angular JS code enhance overall performance, or is it specifically focused on loading speeds?

I currently have 40-60 scripts in my index, with most of them being Angular. I am interested in combining them into a single script for production purposes. Is this possible? Will all the logic still work correctly? And which library is recommended for th ...

Combining Mongoose OR conditions with ObjectIDs

After querying my Team schema, I am receiving an array of ids which I have confirmed is correct. The issue seems to lie in the fact that both home_team and away_team are ObjectIDs for the Team Schema within my OR statement. Team.find({ 'conferenc ...

updating the v-model in Vue.js datepicker retains the previously set value while setting a new date

When using the template, the endDate updates as expected. However, there seems to be an issue when the filtersChanged method is called with the @selected attribute - the updated value is not the new one but rather the previously set value. <template&g ...

Perform a task upon clicking the JavaScript menu

Implementing dropdown menu items using a text link with JavaScript and CSS. You can view a demo here. I am looking to trigger an action when each menu item is clicked. Currently, they are not behaving as expected. HTML: <span class="inline-dropdown- ...

Having trouble decoding JWE using the NPM Jose library

Although I can successfully decrypt a JWE using an older version of jose, I'm facing difficulties in utilizing the latest version API. The headers of my token are as follows: { "alg": "A128KW", "enc": "A128CBC-H ...

Ensure that the input box expands to occupy the entire HTML page

After reviewing numerous pages and questions related to this topic, I have located the correct solution but am struggling to implement it. My goal is to achieve a similar outcome to the second question, but I'm having difficulty figuring out how to do ...

Retrieve all populated fields on the second tier using Node.js and Mongoose

Do you have any insights to share on Node.js and mongoose? I've defined a mongoose schema and when I use findOne(), it returns a document with multiple elements under the "resource" key. Below is an example of how the document looks like: { "met ...

What is the quickest method to perform a comprehensive comparison of arrays and combine distinct objects?

I am currently working with NextJS and Zustand and I have a state in Zustand that consists of an array of objects: [{a:1, b:2}, {a:2, b:3}] Additionally, there is another incoming array of objects that contains some of the existing objects as well as new ...

Troubleshooting Socket.IO Communication: Client's emits not reaching server

I have implemented a real-time notification service in a web app using Express and Socket.IO. The client can successfully connect to the server and receive emits from it. However, I am facing an issue where the server is not receiving emits from the client ...

Executing actions on events in a Basic jQuery sliderLearn how to handle events and execute

I utilized the slider from the bjqs plugin at after reviewing the documentation, I noticed it only offers options and lacks events/functions. I am referring to events/functions like onSlideChange and onSlideDisplay. While other plugins such as bxslid ...

Can you explain the contrast between uploading files with FileReader versus FormData?

When it comes to uploading files using Ajax (XHR2), there are two different approaches available. The first method involves reading the file content as an array buffer or a binary string and then streaming it using the XHR send method, like demonstrated he ...

Tips for positioning a div next to an input box when it is in focus

I am working on a scenario where I have used CSS to extend the search box when focused. The idea is that when the search box is focused, it should decrease in size and a cancel button should appear next to it. This is the CSS code I am using: .clrble .fr ...

Creating a sequence of lights that alternate between on and off

I need to dynamically manage 5 on/off lights using Angular. These lights are connected in parallel to a working slider, sharing the same scope. The logic is simple - when the slider is at position 3, lights 1, 2, and 3 should be ON, while lights 4 and 5 sh ...

Encountering Babel issues while incorporating npm package into React Native project

Currently, I am developing a React Native application. In an attempt to enhance my application, I decided to incorporate the npm package available at this link: https://github.com/MagicTheGathering/mtg-sdk-javascript/ Despite trying various import statem ...

Performing AJAX requests to dynamically update multiple DIVs

Encountering difficulties with adding additional input fields to a page, each of which contains jquery code for appending more select boxes related to them. The base html setup is as follows: <p id="add_field"> … </p> <div class="show_sub ...

The method by which AngularJS identifies the appropriate property within a return value

In Angular, watchers are utilized to identify property changes and trigger a listener function. An example of a watcher declaration is shown below: $scope.food = "chicken"; scope.$watch( function() { return food; }, function(newValue, oldValue) { ...

Tips for showcasing unique keywords in Ace Editor within the Angular framework

Can anyone help me with highlighting specific keywords in Angular using ace-builds? I've tried but can't seem to get it right. Here's the code snippet from my component: Check out the code on Stackblitz import { AfterViewInit, Component, ...

Add new content to an existing JSON file in a Node.js environment

I'm encountering an issue while attempting to insert new text into an existing JSON file. I've experimented with writeFileSync and appendFileSync methods, however the added text does not maintain JSON formatting even when utilizing JSON.stringify ...

The proper translation of the HTML encoded string is not being rendered accurately within AngularJS

I am dealing with an HTML encoded string that looks like this: Sign up and get &lt;span class=&quot;strong&quot;&gt;Something for FREE!&lt;/span&gt; When I implement ngSanitize and ng-bind-html in my template as shown below: ...

A comprehensive guide on troubleshooting the toggleComplete functionality for React Todo applications

When you click on an item in the to-do list, it should show a strikethrough to indicate completion. However, when I try clicking on an item, nothing happens. Here is my toggleComplete function and where I am attempting to implement it: class ToDoForm exten ...