The current date is indicating that the date string provided is invalid for interpretation by dayjs()

Have you tried using DayJs?

If you're working on the browser, specifically with Firefox + Vue + typescript, here's my date string:

2021-02-05 12:00 AM

However, when I include the AM/PM in the code like this:

const dateObj: any = dayjs('2021-02-05 12:00 AM').format('YYYY-MM-DD hh:mm A');

The dateObj output is always "Invalid Date". Removing the "AM" from the string allows it to parse correctly. Even testing with an online tool like this one gives me a strange result:

NaN-NaN-NaN NaN:NaN PM

Interestingly, without the "AM," everything works fine for me.

Any thoughts or suggestions on how to resolve this issue?

EDIT: It seems to work on Chrome but not Firefox...

Answer №1

Firefox Bug

Upon close examination of the code, you will notice that the day string is being passed through the Day constructor like so: new Day('2021-02-05 12:00 AM'). Unfortunately, Firefox does not support this particular day string format, unlike Chrome.

Optimal Solution

The dayjs documentation suggests:

For reliable parsing results with non-ISO 8601 strings, it is recommended to use String + Format.

If you insist on using the above format, a plugin needs to be used as indicated here

To ensure compatibility across all browsers, make the following changes:

import customParseFormat from 'dayjs/plugin/customParseFormat'
import dayjs from "dayjs"

dayjs.extend(customParseFormat)

const yourDate = dayjs('2021-02-05 12:00 AM', 'YYYY-MM-DD HH:mm A')

Answer №2

To make it function properly, you'll require a specific plugin:

  import moment from 'moment'
  import customPlugin from 'moment/plugin/customPlugin'
  
  moment.extend(customPlugin)

Once you have added the plugin, your code should work as intended:

https://momentjs.com/docs/en/plugin/custom-plugin

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

Transforming all numbers to a consistent scale with the help of Numeral JS

Is there a way to customize the output of the numeral.js function so that it always returns numbers in thousands? For example, converting 1000000 to 1000k and 100 to 0.1k. console.log( numeral(1000000).format('0a') ); <script src="https ...

Generating an HTML table with JSON data in JavaScript

I'm still struggling with JavaScript as a beginner, so please bear with me and provide guidance step by step. Also, try to avoid overwhelming the comments with links as it confuses me. This is an attempt to bypass the CORS issue. <!D ...

Can you explain the functionality of $on.constructor in AngularJS?

Recently, I attempted an XSS challenge on the PortSwigger labs website. You can find the challenge here. This is my solution to the XSS challenge: {{$on.constructor('alert(1)')()}} However, since I have no prior experience with AngularJS, I&apo ...

What are the steps to retrieve a Json Object from an Array while extracting information from Rapid API?

Utilizing axios to fetch data from a GET API on RapidAP returns an array of JSON objects, as illustrated in the images below. How can I implement Typescript within React to specifically extract the data of these JSON objects from the array according to my ...

The outputs of base64(sha256(data)) from nodejs crypto and CryptoJS are showing discrepancies

In my setup, I have a node server and a react-native app. The node server utilizes the crypto module for all cryptographic operations, while the react-native app relies on the crypto-js library due to the unavailability of crypto. You can find a sample co ...

utilizing Vue for rendering server side and populating data

Currently in the process of refactoring an app and converting all the base code into vue. One of the key requirements is to implement server side rendering. I've been studying the Vue SSR example along with the Hacker News example to help me grasp th ...

Solve TypeScript React error TS(2339) by resolving issues with extending a React.FC and using static property of type JSX.Element for uninitialized components

Currently, in VSCode, the typescript compiler is at TypeScript React 4.4.2 and it's pointing to a TS(2339) error: Property 'Col' does not exist on type 'FC<GridProps>'. I have attempted to add this prop to GridProps: export ...

Guide on updating post scheduling functionality from Strapi v3 to v4

I am attempting to recreate the scheduled posts functionality from STRAPI v3 for strapi v4 However, I am encountering an issue with the update function. Am I missing a filter, some new formatting, or parameters? config/server.js schedule = require(' ...

Managing an unexpected variable when making an AJAX request

Here is a code snippet that I am working with: var User = { get: function (options) { var self = this; $.ajax({ url: options.url, success: function (data, response) { self.nextPageUrl = data.pagination.next_page; opt ...

Choose a selection from the options provided

This is a sample for demonstration purposes. I am trying to display an alert with the message "HI" when I click on Reports using the id main_menu_reports. My attempted solution is shown below. <ul class="nav" id='main_root_menu'> & ...

The accuracy of the resulting data cannot always be guaranteed after the completion of each function execution. Calculate the function once

Using promises isn't exactly the same in this scenario - as the result depends on multiple service calls being made to populate an array of car makes. <td ng-show="IsOK(obj)" class="text-center"> <img ng-show="GetStatus(obj)=='&apos ...

Tips for preventing FormLabel components from turning blue when a radio button is selected

Currently, I am working on a Reactjs project that utilizes Material Ui components. In this project, I am tasked with creating a form to generate a new event where users can select the event location type from three options - In-Person, Hybrid, and Virtual ...

Can we verify if this API response is accurate?

I am currently delving into the world of API's and developing a basic response for users when they hit an endpoint on my express app. One question that has been lingering in my mind is what constitutes a proper API response – must it always be an o ...

The browser prevented the script located at “http://127.0.0.1:5500/assets/platform.png” from loading due to an invalid MIME type of “image/png”

Sorry if this question seems repetitive, but despite extensive searching, I haven't been able to find a solution to my specific problem. I am currently working on developing a basic JavaScript game, but I'm facing challenges when it comes to impo ...

Bringing an AMD module into a Mocha test

I recently encountered an error while using Mocha to test code that was exported as an AMD module. When running the Mocha test, I received the following error message: ReferenceError: define is not defined at Object.<anonymous> (/home/malintha/proje ...

Execute the controller function once all asynchronous calls to the Angular service have finished

I have integrated the Angular Bootstrap Calendar using a custom cell template and cell modifier. Within my controller, I need to retrieve configuration data from a service that is required by the cellModifier function before it is executed. (function() { ...

Vue: Issue with fetching data resulting in data not loading

I've encountered an issue where data isn't loading after a fetch request. Here's the code snippet in question: <template> <ion-page> <ion-header> <ion-toolbar> <ion-title> ...

Calculating Time Difference in JavaScript Without Utilizing moment.js Library

I have two timestamps that I need to calculate the difference for. var startTimestamp = 1488021704531; var endTimestamp = 1488022516572; I am looking to find the time difference between these two timestamps in hours and minutes using JavaScript, without ...

Is there a way to manipulate the checkbox using the filter?

I'm struggling to create a controllable checkbox that will be checked if the post id matches an id from another array. I want the checkbox to add the post id to a bookmark array when clicked, and I need it to be controllable. The Redux store provides ...

What is the most efficient way to select all checkboxes with jQuery?

I'm not proficient in jQuery, but I attempted to create a script for my application to check all checkboxes, with no success. I first tried using the attr method, and then attempted the prop method, but it seems I'm missing something. Here is my ...