Can Date.parse be utilized within an Angular expression?

I am struggling with the code below:

function Ctrl($scope)
{
    $scope.dt = new Date('2012-07-16T00:00:00');
    var format = 
    {
    day: '2-digit',
      month: '2-digit',
      year: 'numeric'
    };
    $scope.dateTimeFormatter = Intl.DateTimeFormat('es-es', format);
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app ng-controller="Ctrl">
In: {{dt}} <br/> 
Angular: {{dt | date:'yyyy-MM-dd HH:mm:ss Z'}}
  <div style="background-color:lightgreen;">
    This is working: {{dateTimeFormatter.format(dt)}}
  </div>
  <div style="background-color:rgb(251, 123, 89);">
    This is not working: {{dateTimeFormatter.format(Date.parse('2012-07-16T00:00:00'))}}
  </div>
</div>

Can anyone help me figure out what I might be doing incorrectly?

Why does the green line function as expected while the red one doesn't?

Answer №1

Attempting to locate Date within the scope ($scope.Date) proved unsuccessful.

To resolve this issue, include the following code:

$scope.Date = Date;

By adding this line, the problem will be resolved:

function Ctrl($scope)
{
    $scope.dt = new Date('2012-07-16T00:00:00');
    var format = 
    {
    day: '2-digit',
      month: '2-digit',
      year: 'numeric'
    };
    $scope.dateTimeFormatter = Intl.DateTimeFormat('es-es', format);
    $scope.Date = Date;
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app ng-controller="Ctrl">
In: {{dt}} <br/> 
Angular: {{dt | date:'yyyy-MM-dd HH:mm:ss Z'}}
  <div style="background-color:lightgreen;">
    This works: {{dateTimeFormatter.format(dt)}}
  </div>
  <div style="background-color:rgb(251, 123, 89);">
    This doesn't?: {{dateTimeFormatter.format(Date.parse('2012-07-16T00:00:00'))}}
  </div>
</div>

Answer №2

When using dateTimeFormatter.format, make sure to pass in a Date object instead of a number. Remember that "The Date.parse() method parses a string representation of a date, and returns the number of milliseconds since January 1, 1970, 00:00:00 UTC" according to mdn.

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

The integration of ngx-translate with an HTTP interceptor is currently experiencing difficulties

Using ngxtranslate for application translation has been seamless so far. However, I am facing an issue with the HttpInterceptor. This interceptor attempts to retrieve data from local storage at the start and displays a dialog prompting you to either load t ...

Which is better for managing checkbox state in React - react-bootstrap or material-ui?

Currently, I am working on a project that involves using checkboxes within a component to display products based on specific features selected by the user. I am seeking advice on how to effectively manage the checkboxes and their corresponding state inform ...

transferring JSON information to a template in a NodeJs application

Currently, I am performing some filtering on my JSON data and storing the result in a variable called driver. The driver variable contains JSON data that I want to pass unchanged to the view. My main query is: How can I effectively send the data stored i ...

The behavior of Elementor lightbox buttons upon being clicked

When using Android, I've noticed that the lightbox briefly displays a semitransparent cyan bar on the left and right buttons when they are pressed. Is there a way to control or prevent this behavior? Any suggestions would be appreciated! Thanks in adv ...

What's causing Angular to not display my CSS properly?

I am encountering an issue with the angular2-seed application. It seems unable to render my css when I place it in the index.html. index.html <!DOCTYPE html> <html lang="en"> <head> <base href="<%= APP_BASE %>"> < ...

Unveiling the secrets of extracting element content using JavaScript (with JQuery) from an HTML object

I have written the code below to access the page "JQueryPage.aspx" and retrieve data from it using jQuery: <script type="text/javascript> $.get ( "JQueryPage.aspx", function(data) { alert("Data Loaded: " + data); ...

What is the best method to choose a random color for the background when a button is pressed?

Does anyone know how to create a button that changes the background color of a webpage each time it is clicked? I've been having trouble with the javascript function in my code. I've tried multiple solutions but nothing seems to work. Could someo ...

What is the correct method to conceal the error message using JavaScript with document.getElementById("failedUpdateMessage").style.visibility = "hidden"

Once I had applied the code to conceal the element identified by the id "failedUpdateMessage", I now want to reveal that hidden element on a certain webpage using html. How can I achieve this using java script? I attempted to change "hidden" to "show" bu ...

Passing props to a wrapped component when utilizing a higher order component in React

While exploring the react documentation, I came across a section on Higher-Order Components that included an example of logging props for a specific component. function logProps(WrappedComponent) { return class extends React.Component { componentWillR ...

Emphasize the importance of paying attention to read-only

Currently, I have a form containing three inputs. The last input has the property of being ‘readonly’, as the user is supposed to fill it by clicking buttons (such as a virtual keyboard) rather than typing manually. Everything functions correctly in th ...

Tips on aligning a span element at the center of an image without losing its mouseover

<div class="pic"> <img src="image.jpg" height="250"/> <span class="text" style="display:none">text here</span> </div> <scriptsrc="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"> </scrip ...

Guide on shifting an element into a different one with the help of jQuery

I'm attempting to relocate an element within another in order to enable a css :hover effect. <ul> <li id="menu-item"> //move into here </li> </ul> <div class="tomove">...</div> 'tomove' is set to dis ...

Securing my JSON Server Data with angularJS: Best Practices

Ensuring Security for JSON Server Data in angularJS I have concerns about protecting the URL of my JSON Server Data within the Controller. How can I safeguard it from any potential vulnerabilities on the client side? The URL for my JSON Server Data can b ...

How does gray-matter function in Node.js affect the matter within?

import fs from 'fs'; import path from 'path'; import matter from 'gray-matter'; const postsDirectory = path.join(process.cwd(), 'posts'); // ... ... ... // export function getPostData(id) { const fullPath = ...

Steps for adding SVGs to a <div> element

While there are numerous solutions on Stack Overflow detailing how to append an SVG in a div, none of them have proven successful for me. This could be due to my lack of experience with SVGs. Therefore, I am generating an SVG on my node server and the ...

Error occurs when attempting to access window.google in Next.js due to a TypeError

I've been working on integrating the Google Sign In feature into my Next app. Here's how I approached it. In _document.js import React from 'react'; import Document, {Html, Head, Main, NextScript } from 'next/document'; expo ...

Encountered an issue with the ProgressPlugin: TypeError - Unable to access property 'tap' of an undefined element

Encountering a Problem with npm run build Here's the issue at hand Compiling client E:\ui\sheraspace_ui\node_modules\webpack\lib\ProgressPlugin.js:223 compilation.hooks.addEntry.tap("ProgressPlugin", entryAdd ...

Guide to authenticating in ServiceStack with Angular SPA using basic authentication

How should I properly authenticate an Angular single page application when the backend service stack is located on a different domain name with CORS? ...

Tips for placing modal box in the exact desired position upon loading

I've been searching for a solution on how to dynamically calculate the position of each image loaded in a Twitter modal box and place the box underneath a custom toolbar element I have created. The situation is depicted in the image. The height of the ...

Error message "Undefined is not a function" occurred while using jQuery's .replace and scrollTop functions

I'm having issues with the scroll function in my code. It doesn't seem to be able to locate the ids in my HTML, even though I can't figure out why. I had a previous version that worked perfectly fine (unfortunately, I didn't save it D:) ...