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>

https://i.sstatic.net/EX7du.png

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

Nested loops seem to override previous results with the final output

I am attempting to iterate through an array of months nested within an array of 'years' in order to calculate a count for each month using a custom angular filter. Initially, I set up the structure I will be looping through in the first while loo ...

Error encountered in Angular10: XHR request for POST failed due to browser blocking HTTP Request to a domain with a similar name

I am encountering an issue with my webpage that consists of a Django REST API and an Angular 10 Frontend SPA. Normally, I can successfully send GET, POST, PUT, and DELETE XHR Requests to my backend without any problems. However, there is a specific API End ...

Having trouble locating the namespace for angular in typescript version 1.5

I am using Angular 1.5 with TypeScript and have all the necessary configurations in my tsconfig.json file. However, when I run tslint, I encounter numerous errors in the project, one of which is: Cannot find namespace angular My tsconfig.json file looks ...

Ways to limit date selection with JavaScript or jQuery

On my webpage, I have two date fields: fromDate and toDate. My goal is to prevent submission if the difference between the dates is more than 7 days. Despite implementing a script for this purpose, it doesn't seem to be working... var d1 = new Da ...

How can you display a set of components in React using TypeScript?

I'm currently working on rendering an array of JSX Components. I've identified two possible methods to achieve this. Method one (current approach): Create the array as an object type that stores the component properties and then build the JSX co ...

Transforming React drag and drop page builder state into a functional html, css, and js layout

Currently, I am in the process of developing a drag and drop UI builder for react-based app frameworks. Before incorporating drag and drop functionality, my main focus is on rendering a page layout based on a structured array stored in the state. I have a ...

A step-by-step guide on how to use the Google Closure Compiler: a

Is there anyone who could assist me in adding a snippet to the basic process of Google Closure Compiler? I have been trying unsuccessfully to do this via JavaScript code. I am using an example snippet from the official npm page, but when I run it, someth ...

Retrieve an item from a MongoDB database using Mongoose

It seems like a simple problem, but my brain is struggling to comprehend the issue at 2 AM. I'm working on creating a profile page that displays basic public information. My approach involves retrieving the user's username from MongoDB based on t ...

What do I need to add in order to connect a controller to a form submission?

Let's set the scene: There are multiple newsletter forms scattered across a webpage, all needing to perform the same action. This action involves making an AJAX request with certain data and displaying a message using an alert once the request is comp ...

External CSS File causing improper sizing of canvas image

I have been working on implementing the HTML5 canvas element. To draw an image into the canvas, I am using the following javascript code: var img = new Image(); var canvas = this.e; var ctx = canvas.getContext('2d'); img.src = options.imageSrc; ...

Display information based on the radio button chosen

I've set up a radio button with options for "no" and "yes", but neither is selected by default. Here's what I'm trying to achieve: If someone selects "no", nothing should happen. However, if they select "yes", then a message saying "hello w ...

Sorting through various data inputs in one JSON file

I have a JSON file containing an array of objects: obj= [{fname:"abhi",age:5,class:"ten",lanme:"kumar" },{fname:"abhi",age:5,class:"ten",lanme:"kumar" },{fname:"abhi",age:5,class:"t ...

Using jQuery and Flask-WTF to achieve live word count in a TextAreaField - a step-by-step guide!

I am interested in adding a real-time word count feature to a TextAreaField using jQuery. I found an example that I plan to use as the basis for my code: <html lang="en"> <head> <script src= "https://code.jquery.com/jquery ...

Filling in the fields based on the data in the JSON

I prefer not to rely on jQuery for this task. If possible, I would like to maintain the presence of <mytag>. The JSON data structure I am working with is as follows: { "datas": [ { "id": "hotel_name", "value": ...

Encountering a Node Js post handling error with the message "Cannot GET /url

This is my ejs file titled Post_handling.ejs: <!DOCTYPE html> <html lang="en" dir="ltr"> <head> <meta charset="utf-8"> <title>POST-Handling Page</title> </head> <body& ...

Tips for adjusting the dimensions of my chart using JavaScript or Jquery

Utilizing DevExtreme widgets for the creation of a line chart in jQuery as shown below: var dataSource = [{"Date Range": "August-2018", Benelux: 194, Czech_Slovakia: 128, ...

Exploring JavaScript and accessing objects

I'm currently working on a small file-manager project in JavaScript and I've encountered an issue with the code. In the `get()` function, I am trying to access the `Content.files` array but it seems like there's some problem with variable sc ...

Challenges with compiling Next.js with Tailwindcss and Sass

I recently created a simple template using Tailwind for my Next.js project. Normally, I rely on Tailwind's @layer components to incorporate custom CSS styles. However, this time I wanted to experiment with Sass, so I converted my globals.css file to ...

Is there a translation issue affecting Chrome version 44?

Recently, Chrome 44 (44.0.2403.89 m) was released and I've encountered some issues with the translate3d feature (on both Mac and Windows versions). This problem is impacting plugins such as fullPage.js and consequently affecting numerous pages at th ...

Managing the triggering of the automatic transition in view models

My question is straightforward and requires no elaborate explanation. Can Durandal be configured to control the use of transitions when transitioning between viewmodels? The motivation behind wanting to disable the animation is as follows: I have a sear ...