I am looking for a way to convert the date format from "yyyy-MM-dd" to "dd-MM-yyyy" in NestJs

I need help with changing the date format from "yyyy-MM-dd" to "dd-MM-yyyy". Currently, my entity code looks like this:

  @IsOptional()
  @ApiProperty({ example: '1999-12-12', nullable: true })
  @Column({ type: 'date', nullable: true })
  birthDate?: Date;

Is there a way to transform it into the desired format "dd-MM-yyyy"?

Answer №1

One way to achieve the desired result is by utilizing the toLocaleDateString method.

function convertDateToString(date: string): string {
    const options = { year: 'numeric', month: '2-digit', day: '2-digit' };
    return new Date(date).toLocaleDateString('en-US', options);
}

Answer №2

Give it a try:

Add a custom function to any desired service

formatDate(dateTime: string): string {
    const datetimeObj = new Date(dateTime);
    return datetimeObj.toLocaleDateString('en-US', {
      day: '2-digit',
      month: 'short',
      year: 'numeric',
    });
}

Here's an example of its usage:

const dateTimeStr = '2023-06-15 14:30';
console.log(this.timeService.formatDate(dateTimeStr));

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

Troubleshooting: Potential Reasons Why Registering Slash Commands with Options is Not Functioning Properly in Discord.js

While working on a Discord bot, I encountered an issue while trying to register a slash command with options for the ban command. The error message I received was: throw new DiscordAPIError(data, res.status, request); ^ DiscordAPIError: ...

Accessing router params in Angular2 from outside the router-outlet

I am currently working on a dashboard application that includes a treeview component listing various content nodes, along with a dashboard-edit component that displays editable content based on the selected branch of the tree. For example, the tree struct ...

An undefined value is encountered in a function within Node.js

To test this code snippet in node.js v6.0.0: x = 3; var foo = { x:1, bar: { x: 2, baz: function() { console.log(this.x); } } }; foo.bar.baz(); var a = foo.bar.baz; a(); An error is thrown: 2 TypeError: Cannot read property &apos ...

Is there a way for one function to access the validation of a nullable field performed by another function?

Below is a TypeScript code snippet. The function isDataAvailable will return true if the variable data is not undefined. However, an error occurs in the updateData function when trying to access data.i++: 'data' is possibly 'undefined'. ...

Difficulties Encountered when Converting HTML to PDF with Puppeteer on AWS Lambda

HTML TO PDF Struggling with the conversion of HTML to PDF using Puppeteer in a Node.js 16 AWS Lambda environment is proving to be quite challenging. Puppeteer's performance seems to vary when deployed on AWS Lambda or serverless setups, despite work ...

The error message thrown by DynamoDB BatchGet is always 'The key element supplied does not align with the schema'

I've been struggling with the DynamoDB batchGet operation for quite some time now. Here's my table definition using serverless: Resources: MyTable: Type: AWS::DynamoDB::Table DeletionPolicy: Retain Properties: TableName: MyTab ...

Managing a unique section within package.json

Having a custom section in my package.json file is something I'm currently working with. Here's an example structure: { "name": "foo", "version": "0.0.1", "dependencies": { ... }, "mySection": { ... } } Retrieving the data from this cus ...

JavaScript does not allow executing methods on imported arrays and maps

In my coding project, I created a map named queue in FILE 1. This map was fully built up with values and keys within FILE 1, and then exported to FILE 2 using module.exports.queue = (queue). Here is the code from FILE 1: let queue = new.Map() let key = &q ...

Learn how to effortlessly move a file into a drag-and-drop area on a web page with Playwright

I am currently working with a drag-zone input element to upload files, and I am seeking a way to replicate this action using Playwright and TypeScript. I have the requirement to upload a variety of file types including txt, json, png. https://i.stack.img ...

React Native is unable to locate node and npm

https://i.stack.imgur.com/0jd8e.png Currently working on developing a fresh react-native application, encountering a particular error. Confirmed that Node and npm are both properly installed, with the PATH set accordingly. ...

Unable to establish connection to MongoHQ using Node.js connection URL

I have successfully set up and run a Node.js app using my local development MongoDB with the following settings and code: var MongoDB = require('mongodb').Db; var Server = require('mongodb').Server; var dbPort = 27017; v ...

The significance of API Input Validation and Steering Clear of Lengthy Conditional Statements

Currently, I am working on ensuring that my API functions correctly even in cases of bad or missing data. At the moment, I have an if statement that checks for any missing inputs. If an input is missing, it returns false, otherwise there is a large else b ...

Automating without a head using Node.js and the Selenium Webdriver

Currently, I am in the process of working with an automation tool that needs to be deployed within an Ubuntu server. My main query pertains to the possibility of utilizing Chrome silently with Selenium Webdriver. Despite attempting the code provided below ...

What is the best way to save a file in each directory that has been accessed?

I am working with a folder structure that contains multiple directories and files. My goal is to create a file in each directory to keep track of which files have been read. This created file will then be used as a condition to decide whether to skip or re ...

Change object values to capital letters

Upon retrieving myObject with JSON.stringify, I am now looking to convert all the values (excluding keys) to uppercase. In TypeScript, what would be the best way to accomplish this? myObj = { "name":"John", "age":30, "cars": [ { "name":"Ford", ...

Ways to access the chosen value from Ionic's popover modal

I have been working on a simple Ionic 4 Angular app and I am using an Ionic popover modal. The code below shows how I open the popover modal in my application: //home.page.ts async openModal(ev: Event) { const modal = await this.popoverController.create({ ...

Is it possible to dynamically pass a component to a generic component in React?

Currently using Angular2+ and in need of passing a content component to a generic modal component. Which Component Should Pass the Content Component? openModal() { // open the modal component const modalRef = this.modalService.open(NgbdModalCompo ...

Issue: Unable to locate the name 'ContactField' in Ionic 2

While attempting to use Ionic2 to save a contact, an error occurs when running the app through the command line. The cordova-plugin-contacts has been properly installed. Below is the code snippet: import { Component } from '@angular/core'; impo ...

Typescript's implementation of AngularJs provider

After creating an Angularjs provider in typescript, I found myself wondering if there might be a more efficient way to achieve the same outcome. My current provider serves as an abstraction for a console logger, with the interface primarily designed to s ...

What is the process for importing a JSON file into a TypeScript script?

Currently, I am utilizing TypeScript in combination with RequireJS. In general, the AMD modules are being generated flawlessly. However, I have encountered a roadblock when it comes to loading JSON or any other type of text through RequireJS. define(["jso ...