Tips on converting a date string in the format 'dd/MM/yyyy' to a date type using TypeScript

I have attempted the following code in order to convert the date from 'yyyy-mm-dd' format to 'dd/MM/yyyy'. However, when I check the typeof() of the result, it shows that it is a string. Is there a method to convert it into only a date?

let convertedDate;
const timestamp = Date.parse(myStringDate);
if (isNaN(timestamp) === false) {
  const newdate = new Date(myStringDate);
  convertedDate = `${newdate.getDate()}/${newdate.getMonth()+1}/${newdate.getFullYear()}`
  return convertedDate;
} else {
  return myStringDate;
}

Answer №1

Here's a suggestion you might find helpful:

const [year, month, day]: string[] = myStringDate.split('-');
const formattedDate = `${day}/${month}/${year}`;

If you need to perform calculations with the date, consider using a library like moment.js for handling dates in various formats.

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

Setting the default value for a dropdown in Angular 2 using Kendo UI

I'm currently facing an issue with creating a dropdownlist using Kendo UI. The problem arises when I try to set a default selected value upon loading the screen. Referring to their documentation, my code is structured like this: HTML: <kendo-drop ...

Implement the usage of plainToClass within the constructor function

I have a dilemma with my constructor that assigns properties to the instance: class BaseModel { constructor (args = {}) { for (let key in args) { this[key] = args[key] } } } class User extends BaseModel { name: str ...

I encountered an issue with Cypress when attempting to utilize a custom command. The error message "TypeError cy.login is not a function" keeps popping up. Any suggestions on how to resolve this

I am currently working on a TypeScript project and I am attempting to write some tests using Cypress. However, I encountered the following error: TypeError - cy.login is not a function. This error occurred during a before each hook, so we are skipping the ...

How to verify in HTML with Angular whether a variable is undefined

When it comes to the book's ISBN, there are instances where it may not be defined. In those cases, a placeholder image will be loaded. src="http://covers.openlibrary.org/b/isbn/{{book.isbn[0]}}-L.jpg?default=false" ...

Discovering the breakpoints for Angular ng-bootstrapUncover the angular ng

Utilizing ng-bootstrap in my latest project has allowed me to easily create a grid with breakpoints, like so: <div class="row"> <div class="col-sm-12 col-md-6 col-xl-4"></div> </div> Although these breakpoints are convenient, ...

An error was encountered at line 52 in the book-list component: TypeError - The 'books' properties are undefined. This project was built using Angular

After attempting several methods, I am struggling to display the books in the desired format. My objective is to showcase products within a specific category, such as: http://localhost:4200/books/category/1. Initially, it worked without specifying a catego ...

Is there a way to automatically populate the result input field with the dynamic calculation results from a dynamic calculator in Angular6?

My current challenge involves creating dynamic calculators with customizable fields. For example, I can generate a "Percentage Calculator" with specific input fields or a "Compound Interest" Calculator with different input requirements and formulas. Succes ...

Angular 2 - Dependency Injection failing to function

I have created two different implementations for an interface and assigned them as providers for two separate components. However, I am encountering the following error: Error: Can't resolve all parameters for ChildComponent: (?). What could be the i ...

Issue with accessing container client in Azure Storage JavaScript library

When working on my Angular project, I incorporated the @azure/storage-blob library. I successfully got the BlobServiceClient and proceeded to call the getContainerClient method, only to encounter this error: "Uncaught (in promise): TypeError: Failed ...

Is it possible for me to use an array as an argument for the rest parameter?

One of the functions in my codebase accepts a rest parameter. function getByIds(...ids: string){ ... } I have tested calling getByIds('andrew') and getByIds('andrew','jackson'), which successfully converts the strings into a ...

The protractor tool is unable to recognize an Angular component when it is displayed on the page

I have implemented end-to-end (e2e) testing on my project, but I am facing issues that are causing my tests to fail. Below is a snippet of my app.po.ts file: import { browser, by, element } from 'protractor'; export class AppPage { public b ...

How to set return types when converting an Array to a dynamic key Object in Typescript?

Can you guide me on defining the return type for this function? function mapArrayToObjByKeys(range: [string, string], keys: { start: string; end: string }) { return { [keys.start]: range[0], [keys.end]: range[1] } } For instance: mapArrayToObj ...

Using TypeScript's generic rest parameters to form a union return type

Right now, in TypeScript you can define dynamic generic parameters. function bind<U extends any[]>(...args: U); However, is it possible for a function to return a union of argument types? For example: function bind<U extends any[]>(...args: ...

What could be causing this TypeScript class to not perform as anticipated?

My goal with this code snippet is to achieve the following: Retrieve a template using $.get(...), Attach an event listener to the input element within the template I am using webpack to transpile the code without encountering any issues. The actual cod ...

Create a function that will always output an array with the same number of elements as the input

Is there a method to generate a function that specifies "I accept an array of any type, and will return the same type with the same length"? interface FixedLengthArray<T, L extends number> extends Array<T> { length: L; } export function shuf ...

How to update a variable in the app.config.json file in Angular 5

I've created a custom asset JSON configuration file called .angular-cli.json to use as default. However, there are certain instances where I need to update specific values within this file but I'm not sure how to go about it. Any suggestions? .a ...

An error was encountered while parsing JSON data in Angular due to an unexpected token

I am currently working on implementing role-based authorization in my project. The goal is to hide certain items in the navigation bar based on the user's role. I encountered an error as shown below. How can I resolve this? service.ts roleMatch(a ...

send the user to a different HTML page within an Angular application

Does anyone have the answer to my question? I need help figuring out where the comment is located that will redirect me to another page if it's false. <ng-container *ngIf="!loginService.verificarToken(); else postLogin"> <ul clas ...

remove a specific element from an array

Hey there! I'm attempting to remove only the keys from an array. Here's the initial array: {everyone: "everyone", random: "random", fast response time: "fast response time", less conversations: "less conversatio ...

The mark-compacts were not efficient enough, they approached the heap limit and as a result, the allocation failed. The JavaScript

Currently working with Angular version 7.2 and encountering an issue when running ng serve: FATAL ERROR: Ineffective mark-compacts near heap limit Allocation failed - JavaScript heap out of memory What does this error mean? How can it be resolved? The ...