How can I resolve the issue of Angular displaying "NaN" instead of a date when converting a date into a

There was an issue with the date format coming from the server, displaying "Thu Jan 07 2016 11:00:40 GMT+0530 (IST)". I managed to convert this date into a more readable format as "1/7/2016 11:00 am". However, my goal is to have the date displayed in mm/dd/yyyy format along with the time in AM and PM 12-hour format. While Chrome browser correctly displays the desired format, when building the project on an iPad, it shows "Nan" instead of the date and time.

Please assist me with resolving this issue.

Below is the code for formatting the date:

This function takes a date object and converts it into DD/MM/YYYY format with a 12-hour clock time.


function formatDate(date) {
    var hours = date.getHours();
    var minutes = date.getMinutes();
    var ampm = hours >= 12 ? 'pm' : 'am';
    hours = hours % 12;
    hours = hours ? hours : 12; // the hour '0' should be '12'
    minutes = minutes < 10 ? '0'+minutes : minutes;
    var strTime = hours + ':' + minutes + ' ' + ampm;
    return date.getMonth()+1 + "/" + date.getDate() + "/" + date.getFullYear() + " " + strTime;
}

The following code snippet extracts the date from JSON data and converts it into the specified format.


var date = new Date(data.Steps.records[i].CreatedDate);

var convertedDate = formatDate(date);
console.log("New date format: " + convertedDate);
data.Steps.records[i].CreatedDate = convertedDate;
console.log("Original date: " + date);

Answer №1

If the value of

data.Steps.records[i].CreatedDate
appears as "Thu Jan 07 2016 11:00:40 GMT+0530 (IST)", it is not recommended to use the Date constructor for parsing. Parsing such strings can yield different results based on the implementation, leading to inconsistencies across different hosts.

For accurate date parsing, it is advisable to manually parse the strings using a custom function or a dedicated library.

Once the date is parsed correctly, formatting it into a string should consider the system settings of the host, resulting in a localized date format.

A sample function provided below demonstrates how to parse the given format. However, for handling various date formats more efficiently, utilizing a library could streamline the process:

var s = "Thu Jan 07 2016 11:00:40 GMT+0530 (IST)"
var t = "Thu Jan 07 2016 01:10:50 GMT+0530 (IST)"
var u = "Thu Jan 07 2016 01:40:10 GMT+0530 (IST)"

function parseDate(s) {

  var months = {jan:0,feb:1,mar:2,apr:3,may:4,jun:5,jul:6,aug:7,sep:8,oct:9,nov:10,dec:11};

  var b = s.split(/[ :]/);

  var offset = b[7].replace(/\D/g, '');
  
  var offSign = b[7].indexOf('+') == -1? 1 : -1;
 
  return new Date(
    Date.UTC(b[3],
    months[b[1].toLowerCase().substr(0,3)],
    b[2],
    +b[4] + (offset.substr(0,2)*offSign),
    +b[5] + (offset.substr(2,2)*offSign),
    b[6]));
}

function formatDate(d) {
  function z(n){return ('0'+n).slice(-2)}
  var hr = d.getHours();
  var ap = hr < 12? 'am' : 'pm';
  hr = hr%12 || 12;
  return z(d.getDate()) + '/' + z(d.getMonth()+1) + '/' + d.getFullYear() +
         ' ' + z(hr) + ':' + z(d.getMinutes()) + ':' + z(d.getSeconds()) + ' ' + ap;
}

document.write(formatDate(parseDate(s)) + '<br>' +
               formatDate(parseDate(t)) + '<br>' +
               formatDate(parseDate(u)));

Edit

Add function to format date string per OP.

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

JavaScript - retrieve only the domain from the document.referrer

I am trying to extract only the domain from referrer URLs. Two examples of referrer URLs I encounter frequently are http://www.davidj.com/pages/flyer.asp and http://www.ronniej.com/linkdes.com/?adv=267&loc=897 Whenever I come across URLs like the ones ...

Choosing a particular svg path in d3.js using JSON attribute

Is it feasible to isolate just one of the SVG paths generated from a geoJSON file using D3? In my scenario, the paths represent different areas on a map. Users can pick an area from a dropdown menu. I aim to utilize the selected value from this list to pin ...

Routing in Next.js to create custom URL slugs for usernames, like (site.com/username), is a

I have a requirement to create username pages on my website, where each username will have its own page like site.com/jack The current folder structure I am using is pages > [user] > index.js, but this setup causes issues when someone tries to acces ...

React component fails to re-render after state change

For the past two days, I've been struggling with this error and can't seem to fix it! I'm currently working on creating a weather app in React which utilizes the API. The app features a Bootstrap Navbar with a search option that allows user ...

I am currently seeking a way to validate if a variable corresponds to the choice made in the dropdown menu. Any suggestions on how to accomplish this task?

I have put together a simple drop down menu. My goal is to grab the currently selected value from the drop down list, store it in a variable, and display it in the console. The ultimate objective is to compare that variable with another one to determine if ...

Customizing Attribute for Material UI TextField

I'm currently in the process of adding a custom data attribute to a TextField component like so: class TestTextField extends React.Component { componentDidMount() {console.log(this._input)} render() { return ( <TextField label= ...

Incorrect positioning on canvas

Is there a way to adjust text alignment within a canvas? Currently, my text is centered. However, when I change the text size, the alignment gets thrown off. Here is the code snippet: <canvas id="puzzle" width="480" height="480"></canvas> ...

Guide to accessing object items in v-for in VueJs

Upon inspection, the following results are being displayed: https://i.sstatic.net/oF4Qe.png https://i.sstatic.net/21aHB.png In the Vue template code provided: <select class="form-select" v-model="post_format.wpml_language"> <option v-for="(l ...

Is there a way to pass attributes to BufferGeometry in THREE.js without using ShaderMaterial?

I've been attempting to make a THREE.js example designed for version 58 compatible with the latest version of THREE.js. You can find the original example here. While I was able to resolve a few errors by simply commenting out certain code, one error ...

How can I eliminate the scrollbar from appearing on all browsers when visiting my website?

I've encountered an issue while building my portfolio with React.js. I'm having trouble removing the scrollbar. I've attempted using overflow: hidden for the parent element and overflow: scroll for the child div, but it's not producing ...

Maximizing Jest's potential with multiple presets in a single configuration file/setup

Currently, the project I am working on has Jest configured and testing is functioning correctly. Here is a glimpse of the existing jest.config.js file; const ignores = [...]; const coverageIgnores = [...]; module.exports = { roots: ['<rootDir&g ...

Converting Node.js Date.toString() output into a time format in Go

My go service is currently receiving data from an external source. Here's how the data appears (in JSON format)- { "firstName": "XYZ", "lastName": "ABC", "createdAtTimestamp": "Mon Nov 21 2 ...

Ways to stop the endless cycle of a node.js script powering a Discord bot

I've developed a Discord bot using JavaScript for node.js that can change a role's color like a rainbow. async function colorChanger (){ for (var i = 0; i < colorArray.length - 1; i++){ myRole.setColor(colorArray[i]); ...

Establish the state as the result of a function

I need to update the state of timeToCountdown with the value stored in allTimeInSeconds. Next, I intend to pass this data as a prop to a component. class Timer extends Component { constructor(props){ super(props); this.state = { ...

Can you explain the function of MathUtils.euclideanModulo and how it sets itself apart from the traditional modulo operation?

I'm a little puzzled by the euclideanModulo function in threejs's mathutils. I understand the concept of the modulo operator, but the euclideanModulo function seems to work differently. ( ( n % m ) + m ) % m I tried researching the meaning of "E ...

When a StaticFiles instance is mounted, FastAPI will issue a 405 Method Not Allowed response

Running a FastAPI application has been smooth sailing until I encountered an issue. In my current setup, the application script is as follows: import uvicorn from fastapi import FastAPI from starlette.responses import FileResponse app = FastAPI() @app.ge ...

Encountering an unforeseen identifier error while attempting to install GitHub using

I am facing an issue with my GitHub repo where I am trying to install Clockwork SMS using npm. However, the console is showing an error message "Uncaught SyntaxError: Unexpected identifier". You can find the website here: . To explain further, I am workin ...

Can the autoscroll offset be adjusted while dragging?

I am developing a single-page application using Vue.js. The user interface consists of three main components: A fixed navbar at the top with a z-index of 2 A fixed sidebar on the left with a z-index of 1, and padding to accommodate the navbar A central ar ...

Cross domain widget ajax request

Our company offers a widget for clients to add to their websites. This widget requires a call to our website to validate user-entered data. However, due to domain restrictions, making ajax calls from the client's website to ours is not permitted. Is ...

Using ng-repeat to filter items within a select box

I'm currently working on updating my article list based on the selected category. I have no issues populating the list with articles, but I'm facing difficulties in populating the category select box and binding a function to its change event. B ...