How can I manually set a date in Angular bootstrap datepicker?

Using the Angularjs Bootstrap datepicker has been a great experience, but I encountered a problem when attempting to select the date using JavaScript. How can I ensure that the selected date in the datepicker matches the date read from a specific object, such as 4/5/1990?

Hint: This functionality is needed when presenting data for user editing.

Review my current code:

HTML

<input type="text" class="form-control" ng-model="Birthdate" id="Birthdate" name="Birthdate" required autocomplete="on" datepicker-popup="dd/MM/yyyy" is-open="opened" max-date="'2015-06-22'" datepicker-options="dateOptions" date-disabled="disabled(date, mode)"
                               ng-required="true" close-text="Close" placeholder="Enter Birthdate"  />

JavaScript

$scope.Birthdate = $scope.users[id].Birthdate;

However, two issues arise with the selected date:

First issue: When the date is 4/5/1986, the day and month are swapped in the date format. For example, 4/5/1990 becomes 5/4/1990.

Second issue: No date is selected if the date is 28/5/1986.

I am seeking assistance on how to have the datepicker select the date exactly as it is read from the object. If the date is 4/5/1990, the datepicker should show that date without any alterations. Similarly, if the date is 28/5/1986, the datepicker should select that date accurately.

Answer №1

Check out this Plunker example: http://plnkr.co/edit/mDHliPweKoUNOAmVv5oo?p=preview

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<pre>Raw date is: <em>{{dt}}</em></pre>
The date retrieved from the server must be in the same format as Raw date for the date picker to accept it. You cannot pass already formatted dates as Model, which is causing the issue.

Answer №2

Query 1: How can I adjust the selected date in a datepicker to be 4/5/1990 when reading data from a specific object? Scenario: If the date is initially set as 4/5/1986, the day and month need to be swapped in the format - for example: 4/5/1990 would become 5/4/1990 Revise today function:

$scope.today = function() {
$scope.dt = "4/5/1990"; };  $scope.today();

Query 2: When no date is selected, such as on 28/5/1986, Solution: Utilize moment.js. It's crucial to avoid setting dates using strings for accuracy; employing a standard library like moment.js is recommended.

$scope.today = function() {
$scope.dt = moment("28/5/1986", "DD-MM-YYYY").format();};  $scope.today();

Moment JS proves to be an excellent tool for date formatting purposes.

Sample: http://plnkr.co/edit/NWQutvl8vXY9YP2LoIZ8

Answer №3

When extracting a date from the datepicker, for example 2015-06-03T15:25:51.211Z, I initially truncate it to just 2015-06-03 before saving it in the database.

The issue arises when trying to bind 2015-06-03 back to the datepicker - it does not accept this format and only recognizes 2015-06-03T15:25:51.211Z instead.

To resolve this problem, I made a change by storing the full date with timestamp as 2015-06-03T15:25:51.211Z in the database. This allowed the datepicker to successfully bind it for editing by the user.

Answer №4

@AbuTaha: One way to tackle this issue is by utilizing moment js library.

$scope.today = function() {
$scope.dt = moment("2015-06-03T15:25:51.211Z", "YYYY-MM-DD").format();  };  $scope.today();

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

Promise and Determination failing to produce results

const { GraphQLServer } = require('graphql-yoga'); const mongoose = require('mongoose'); mongoose.connect("mongodb://localhost/test1"); const Todo = mongoose.model('Todo',{ text: String, complete: Boolean }); const ...

Limiting the scope of the jQuery scrollToFixed functionality within various nested DIV elements

I have been grappling with this issue for the past two days without success. I am utilizing the ScrollToFixed plugin from https://github.com/bigspotteddog/ScrollToFixed and my goal is to restrict the fixed positioning within a parent DIV. Despite scouring ...

Parsing JSON data using PHP and AJAX decoding

I have been searching for a way to pass parameters between the server and client, but I am struggling to find a solution that works. Despite reading extensively online, I have not been able to come up with a functioning solution. Client Side function sen ...

Changing a JavaScript string into an array

I have extracted an array of objects from a hidden HTML input field and received the following string: "{"id":"1234","name":"john smith","email":"<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="dab0a9b7b3aeb29ab8b6bbb2f4b9b5b7" ...

Ways to identify input that has been altered dynamically

I'm currently trying to figure out why I can't seem to detect any input changes with the code snippet below: $("#fname").on("change", function () { console.log("The text has been changed."); }); $("button").o ...

What sets apart $document from $window.document in Angular?

After experimenting with the code on JSBin, I noticed that the first snippet successfully retrieved the canvas object, while the second one did not. JSBin: http://jsbin.com/natavejasa/1/edit?html,js,output var canvas = $window.document.getElementById(&ap ...

Modify the color of the text input by the user in an AJAX-enhanced text box

After successfully implementing an autocomplete textbox using AJAX Autocomplete, I decided to enhance the feature with some Fuzzy logic. Now, as the user enters 3 characters, my database returns a list of records that match those characters. The search re ...

Nuxt Page Featuring One Exclusive Product

I am just getting started with Nuxt and I'm in the process of creating a Single Product. I have some questions: How can I generate multiple pages using SSR and create a unique HTML for each page? Should CSR be developed first before implementing SSR, ...

What is the process for testing bootstrap techniques in a node environment?

An issue arose with a React component where the componentDidMount() function includes the following line: $('[data-toggle="tooltip"]').tooltip(); During testing, an error message is displayed: TypeError: $(...).tooltip is not a function The ...

Synchronous execution of functions in Node.js

I need to ensure that func2 is only called after func1 has completed its execution. { func1(); func2();// } However, the issue arises when func1() starts running and func2() does not wait for it to finish. This leads to a runtime error as func2() require ...

Recurrence of solely the middle segment of the separator's background picture

I have a unique divider image with fading top and bottom parts. I'm wondering if it's possible to use a sprite and 3 divs to only repeat the middle section, considering that my height is variable. Do I need separate images for the top, middle, an ...

When utilizing ui-router, the root url will automatically redirect to a state with an empty url

My parent state has a URL mapped for '/' and when I visit the root, like this example: http://localhost:8081/sin/TPW/, it automatically redirects me to a child state with an empty URL. I'm puzzled as to why this specific child state is bein ...

Guide to displaying a table enclosed in a div based on a selected value in a select dropdown?

I am attempting to retrieve the table options using the select question-picker: Here is what I have tried: $(document).ready(function() { var question_container = $('.question-picker option[value="1"]').parent(); console.log(question_cont ...

Incorporating additional text following the creation of an image composite using HTML5

I am facing an issue with positioning two images on a canvas using HTML5. Despite changing the x and y properties, the images remain stuck at the top left corner (0, 0). This is different from how I can position text easily on the canvas. <canvas width ...

The distortion of Blender animation becomes apparent once it is imported into three.js

I've been working on a project where I'm incorporating animations into a scene using a combination of blender and three.js. It took me several hours of trial and error to finally get the model and animation successfully imported into three.js. I ...

Having trouble with my sorting algorithm - am I overlooking something obvious?

function Controller($scope) { var sortItems = [ { "text": "Second", "a": 2 }, { "text": "Fifth", "a": 5 }, { "text": "First", "a": 1 }, { "text": "Fourth", "a": 4 }, { "text": "Third", "a": 3 } ]; va ...

How can I save variable values to a text file or Excel file using Cypress.io?

Is there a way to write the values of a variable on a Text or Excel sheet? I have a variable called tex that stores string values, and I want to output these values onto text files or an Excel sheet if possible. beforeEach(() => { cy.visit('ht ...

Rails 6 not displaying Javascript as intended

I am a beginner at this, but so far everything seems to be functioning smoothly. On my page, users can upload and delete photos without any issues. The uploading and deleting processes work perfectly fine. However, I am facing an issue where the page does ...

Error encountered when injecting ngRoute into AngularJS mobile UI design

I'm encountering an issue with ngRoute injection... I have ensured that the file angular-route.min.js is included in the correct path, but I am still receiving this particular error Below is the JavaScript code snippet: (function() { var app = an ...

Tips for sending <p> data to a router function with HTML

I am currently working on a page where users are presented with a list of unverified accounts, each containing its own form element. Each form has a "submit" button that triggers a POST call to /verify. However, I am facing an issue where the data within t ...