Incorrect date format used in formatWithOptions function leads to a Range Error: Invalid time value

I am looking to showcase the date of each entry (date, text, question, answer) stored in a json database within a lit element in a js module. The format for the date in the json db is compliant (refer to this post). For example:

"2021-12-24T21:06:06.773Z"

Here is the relevant code:

import { formatWithOptions } from "date-fns/fp";
import compose from "crocks/helpers/compose";

...

const newDate = (x) => new Date(x);


const formatDateWithOptions = formatWithOptions(
  {
    awareOfUnicodeTokens: true,
  },
  "d MMMM, yyyy, h:mm a"
);

const prettyDate = compose(formatDateWithOptions, newDate); // however, this is throwing an error indicating an invalid date

When ${prettyDate(date)} is used within a lit element, it triggers

RangeError: Invalid time value.

As per the date-fns documentation, calling formatWithOptions() with "d MMMM, yyyy, h:mm a" should work. There's a discussion on this post addressing the same error but using a different function (formatDistanceToNow). Can you identify where I might be making mistakes with my variables?

Answer №1

If the variable x is not defined, the code snippet below will result in an invalid date being generated.

const generateNewDate = (x) => new Date(x);

Furthermore, it is essential to remember to invoke the compose function in order to supply an input for the generateNewDate function.

The modified code provided here should run correctly:

const EXAMPLE_DATE_STR = "2021-12-24T21:06:06.773Z";

const generateNewDate = x => {
  if (x === undefined) { return new Date(); }
  return new Date(x);
}

const formatDateWithOptions = formatWithOptions(
  {
    awareOfUnicodeTokens: true,
  },
  "d MMMM, yyyy, h:mm a"
);

const formattedDate = compose(formatDateWithOptions, generateNewDate)(EXAMPLE_DATE_STR);

console.log(formattedDate); // Output: 24 December, 2021, 9:06 PM

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

Attempting to insert a dynamic variable into a jQuery click event selector

I'm facing an issue where I am attempting to use a variable as a selector within a click event for a dynamically generated row in a table. When I manually enter the class name, the row click event works perfectly. However, when I try to use the variab ...

Different Methods for Establishing XMLHttpRequests

I'm currently diving into the world of AJAX and looking into different methods of creating HttpRequests. So far, I've brainstormed a few approaches: function one() { if(window.XMLHttpRequest) { xhr = new XMLHttpRequest(); alert('Oth ...

Using eslint with the vue plugin allows you to specify which object fields to ignore in

My ESLint rule setup includes the following: "vue/script-indent": [ "error", 4, { "baseIndent": 1, "switchCase": 1, "ignores": [ "[init.type=\"ObjectExpression\"]", "[init.type= ...

Preventing duplicate index values in JavaScript loop iterations

I have a specific scenario in JavaScript where I need to traverse an array and check if the index matches any predefined options. If it does, I either push or print the option once. Here is the array: ["ITEM1", "dummyData1", "dummyData2", "ITEM2", "dummyD ...

Is it true that nodejs's q denodeify doesn't execute functions in then, fail, or fin blocks?

Here is the code I am currently working with: var q = require('q'); function Add(cb) { var a,b,c; a = 5; b = 6; c = a + b; console.log("inside"); cb(null, 123); } var add_promise = q.denodeify(Add); add_promise(function() {console ...

Utilize event delegation to retrieve the data attribute

Working great for me, able to access data-club-id: <!-- example --> <a class="clubCode" href="" data-club-id= "1234">join with the code</a> $("a.clubCode").on("click",function(e){ e.preventDefault(); var clubId = $(this) ...

Is it possible to refresh an iframe with PHP once a certain condition is satisfied?

I have a situation with two pages - one is my PHP script and the other is an HTML page containing two iframes. > <html> > > <iframe name=1></iframe> <iframe name=2></iframe> > > </html> Currently, ifram ...

Deleting a database table row with a click of a button

I am working with a table structure in my HTML: <table class="table" id="mytable"> <tr> <td>Column 1</td> <td>Column 2</td> <td><button type="submit" class="btn removeButton">Remove</button& ...

Is there a way to implement seamless scrolling within an absolute element using Jquery?

Hey there! I recently implemented smooth scrolling on my website, but it seems to only work on single-page layouts. How can I make it function properly within an absolutely positioned scrollable element? Here are the link to my website and the correspond ...

What is the method to determine the inviter on Discord.js?

Hi there! I'm currently working on an Invite Logger and could use some assistance. I'm having trouble figuring out how to identify the user who invited another user. client.on('guildMemberAdd', async (member) => { const channel = ...

The element type is not valid: it should be a string for built-in components or a class/function for composite components, but it is currently an object in a React project

In the process of developing a React app to explore MUI capabilities, I encountered an error in my browser: The issue reported is: Element type is invalid - expected a string (for built-in components) or a class/function (for composite components), but rec ...

Converting string to JSON format by splitting it based on names

I recently manipulated a string containing the values "title:artist" by utilizing the str.split method : res = song.split(":"); The resulting output is as follows: ["Ruby","Kaiser Chiefs"] Now, I am curious about how to include the name in this array f ...

What is the process for obtaining an AccessToken from LinkedIn's API for Access Token retrieval?

We have successfully implemented the LinkedIn login API to generate authorization code and obtain access tokens through the browser. https://i.sstatic.net/0dfxd.png Click here for image description However, we are looking to transition this functionality ...

Load a partial view in MVC using Ajax with a complex data structure

Within my main view, I have a section that loads a partial view containing data. Here is the code snippet that is executed upon initial loading: <div id="customerdetailsDIV" class="well main-well clearfix"> @Html.Partial("_customer_details", Mod ...

Three.js: How to Make a Camera Circle a Sphere?

How can we use Three.js and JavaScript/ WebGL to create a camera that orbits a sphere at a fixed height, with a fixed forward speed, and maintaining a fixed orientation in relation to the sphere? The user should only be able to steer the camera left and ri ...

Is it possible to redirect the client to a different HTML file after they input a number?

Following a submission of numerical input, I am looking to navigate from the index.html file to another HTML file or similar destination. Could someone provide assistance? Below is the code I have written: <!DOCTYPE html> <html lang="en&quo ...

Exploring Angular 2 Routing across multiple components

I am facing a situation where I have an app component with defined routes and a <router-outlet></router-outlet> set. Additionally, I also have a menu component where I want to set the [routerLink] using the same routes as the app component. How ...

What is preventing this from being passed to the subsequent component in ReactJS?

I am trying to get the Portfolio class to utilize the this.prompt method from the Title Bar class. Despite extensive research, I have not been able to find a definitive solution for this yet. Currently, my screen is just blank. Below is the content of my ...

Retrieving a boolean value (from a JSON file) to display as a checkbox using a script

Currently, I am utilizing a script to fetch data from a Google Sheet $.getJSON("https://spreadsheets.google.com/feeds/list/1nPL4wFITrwgz2_alxLnO9VBhJQ7QHuif9nFXurgdSUk/1/public/values?alt=json", function(data) { var sheetData = data.feed.entry; va ...

Having trouble importing a CSS file into a Vue.js single file component?

I am attempting to include 2 CSS files within the style tag of my Vue.js single-file component. <style > @import '../assets/styles/jquery-ui.js.css'; @import '../assets/styles/jquery-ui.css'; </style> However, I am ...