The date displayed on the popup calendar is local time, while the date selected is in Coordinated

Is there a way to maintain the selected date in UTC format?

I am experiencing an issue where the pop-up calendar does not synchronize with the selected datetime.

For instance, when I click on 08/13 and the selected date shows as 08/12.

This discrepancy occurs because although it is 08/13 in my timezone, it remains 08/12 in UTC timezone

Code Snippet:

  <div class="col-sm-10" ng-click="open($event)">
    <input type="text" class="form-control ng-pristine ng-untouched ng-valid ng-isolate-scope ng-valid-date ng-valid-required" datepicker-popup="yyyy/MM/dd" is-open="opened" datepicker-options="dateOptions" ng-required="true" close-text="Close" required="required" aria-required="false" aria-invalid="false" ng-model="form.start_date" />
  </div>

JS controller:

    app.controller('FlightSkuStartDatepickerCtrl', ['$scope',
        function($scope) {
            // Disable weekend selection
            $scope.disabled = function(date, mode) {
                return (mode === 'day' && (date.getDay() === 0 || date.getDay() === 6));
            };

            $scope.toggleMin = function() {
                $scope.minDate = $scope.minDate ? null : new Date();
            };
            $scope.toggleMin();

            $scope.open = function($event) {
                $event.preventDefault();
                $event.stopPropagation();

                $scope.opened = true;
            };

            $scope.dateOptions = {
                formatYear: 'yy',
                startingDay: 1,
                class: 'datepicker'
            };
            $scope.formats = ['YYYY/MM/DD'];
            $scope.format = $scope.formats[0];
        }
    ]);      

Answer №1

If your data is already stored in UTC, why struggle with changing it? If you need to convert from UTC to a different timezone, consider using the moment for Angular library. Remember to specify the timezone when converting. Here's an example:

function convertUtcToTimeZone(date, current_tz) {

            var offset = moment(date).tz(current_tz).utcOffset();
            var returnObj = {
                "day": "",
                "time": ""
            }
            returnObj.day = moment.utc(date).tz(current_tz).utcOffset(offset).format('dddd');
            returnObj.time = moment.utc(date).tz(current_tz).utcOffset(offset).format('HH:mm:ss')

            return returnObj;
        }

You can input the date parameter as your chosen date from the UI and current_tz as your timezone. Make sure to use the timezone format like "America/Los_Angeles."

function convertTimeZoneToUTC(date, current_tz) {

            var offset = moment(date).tz(current_tz).utcOffset();
            offset = offset * -1;
            var returnObj = {
                "day": "",
                "time": ""
            }
            returnObj.day = moment.utc(date).tz(current_tz).utcOffset(offset).format('dddd');
            returnObj.time = moment.utc(date).tz(current_tz).utcOffset(offset).format('HH:mm:ss')

            return returnObj;
        }

The second function allows you to save your selected date as UTC. Ensure you provide the correct parameters. For instance, if you're in "America/Los_Angeles," specify your timezone accordingly to convert it to UTC. Use these functions to synchronize your UI and backend effectively.

Answer №2

The updated ui-datepicker now offers a simpler solution for handling timezones.

   ng-modal-options='{"timezone":"utc"}'

This eliminates the need for the timezone component in the date.

For older versions:

To remove the timezone from the date, one could create a directive for reusability...

myapp.directive("dateToIso", function () {   
    var linkFunction = function (scope, element, attrs, ngModelCtrl) {

        ngModelCtrl.$parsers.push(function (datepickerValue) {
            return moment(datepickerValue).format("YYYY-MM-DD");
        });
    };

    return {
        restrict: "A",
        require: "ngModel",
        link: linkFunction
    };
});

You can implement it as shown below

  <input ng-model='abc' date-to-iso ui-datepicker>

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

Combining Rails API with AngularJS and IonicFramework

I'm embarking on a new project and feeling unsure about my chosen setup/approach. The project involves creating a list directory that doesn't require high computing power. My initial plan is to develop a website using Rails Api and AngularJs (al ...

Feeling trapped during the process of setting up a intricate jQuery Image Slider

I've hit a roadblock while trying to make changes to the slider located at THIS URL. In the current setup, each thumbnail corresponds to one main display image. Clicking on a thumbnail displays a single image and then proceeds to slide to the next th ...

Reduce the combined character value of the title and excerpt by trimming the excess characters

I am seeking a solution to trim the total character count of a post title and excerpt combined. Currently, I can individually adjust the excerpt through theme settings and the post title using JavaScript. However, due to varying title lengths, the height ...

"Utilizing Typescript and React to set a property's value based on another prop: A step-by

Is there a way to create a dynamic prop type in React? I have an Alert component with various actions, such as clicking on different components like Button or Link. I am looking for a solution like this: <Alert actions={[{ component: Link, props: { /* ...

Troubleshooting JSONP Implementation with JQuery: Scope versus Async Problems

I've been trying to call a JSONP service using the $.ajax function: $.ajax({ url: jsonpURI, dataType: "jsonp", jsonpCallback: callback, success: function () { console.log("Success"); }, error: function (err) { ...

The URL not functioning properly after including the .active class with JQuery

This website is built on the Shopify platform. To highlight an active link in a subcategory list, I am using JQuery and CSS to add the .active class to the element. However, after adding the JQuery code, the link element is not functioning properly and d ...

Function is raising an error with the wrong value or text

I am currently testing a form that I am in the process of developing. My goal is to have different values returned each time I click on a different item from the dropdown menu. If this explanation isn't clear, please take a quick look at my pen for cl ...

Issues with Rails comments not displaying properly when using ajax requests

I've implemented ajax comments in my rails app and while I can see the comments are being processed in the console, they're not displaying/rendering on the page. My javascript appears to be functioning correctly, but I'm unsure where the iss ...

JavaScript allows users to create a single string by merging multiple strings positioned at various points

Let's say we have 3 strings: s1 = "ab", s2 = "cd", s3 = "ef". The task is to form a new string by merging s1, s2, and s3. The twist here is that the user has the freedom to choose the positions of these 3 strings. For example: s1 - position 3; s2 - ...

When working with React and trying to update data using the useEffect hook, I encountered an issue with an Array data. Unfortunately, using map or Object.keys(data).map did not produce the desired results. Can anyone provide guidance on

After using the useEffect hook to update the data, I noticed that the data is an array when inspected in the DEV tools. However, when attempting to traverse the data using the map function, an error stating 'data.map is not a function' is returne ...

Using jqgrid to customize column header tooltips which are distinct from the actual column label

From what I gather, there are multiple methods for setting distinct column header tooltips. At the moment, my approach involves using jQuery's .attr() to set the tooltips. I'm curious if there is a more streamlined way to save the custom header ...

Express.js POST Request Not Being Accepted | 404 Error Detected

I am encountering difficulties implementing PayPal on my website. Whenever I attempt a post request, including using Postman, I receive a standard 404 error page instead of the expected response. The console shows no errors, leading me to believe that the ...

Execute JS function when navigating back in history

I recently came across an article on browser bfcache in Stack Overflow. I decided to test it out on Safari Version 7.0.5 (9537.77.4) and noticed that when I click the back button in history, the JavaScript does not execute. How can I ensure that my JavaS ...

"Issue with Material-ui Autocomplete where the defaultValue does not function properly

The defaultValue was set to "Chairs" but it doesn't seem to be working as expected. Here is the code snippet: import React, { useState } from "react"; import TextField from "@mui/material/TextField"; import Autocomplete from "@mui/material/Autocomple ...

The process of altering the color of a table row in JavaScript can be done after dismissing a pop-up that was triggered by a button within the same row

I am tasked with changing the color of a specific table row based on user interaction. The table consists of multiple rows, each containing a button or image. When the user clicks on one of these buttons or images, a popup appears. Upon successful data sub ...

A guide on displaying information from an array of objects using MongoDB and AngularJS

I need assistance with appending data to a div using ng-repeat. https://i.sstatic.net/Z9VGw.png Currently, I am working with angularjs and MongoDB but without mongoose. Any guidance on this would be greatly appreciated. Here is an array of objects retri ...

Using jQuery to toggle CSS properties

I'm having trouble switching between a CSS column layout and a normal layout for a div element with the ID 'article'. The jQuery script I wrote doesn't seem to work properly, as the entire thing disappears. Can anyone advise me on how t ...

Tinymce removes <html> tags from the output displayed in a textarea

I have created my own small CMS using Tinymce. When I insert plain text in pre tags, the code displays correctly on the website. However, when I update the editor, the HTML tags are removed. My Tinymce setup: <script type="text/javascript"> tinyMCE ...

Steps to create a clickable button wrapper label in React

Contained within the components below: <CheckboxGroupLabel htmlFor={option.label}> <FormCheckbox onClick={() => onChange} key={option.label} defaultChecked={defaultChecked} {...rest} /> {option.value} ...

Storing JavaScript variables in a database: A step-by-step guide

For the past few days, I've been working with CakePHP and trying to save a javascript variable into a MySQL database using AJAX (jQuery). Here's the code I've been using: <!-- document javascripts --> <script type="text/javas ...