Generating a date without including the time

I recently started working with React (Typescript) and I am trying to display a date from the database without including the time.

Here is my Interface:

interface Games {
g_Id: number;
g_Title: string;
g_Genre: string;
g_Plattform: string;
g_ReleaseDate: Date;
g_Price: number;}

Below is my output method:

private static renderGamesTable(games: Games[]) {
    console.log(games)
    return <table className='table'>
        <thead>
            <tr>
                <th>Title</th>
                <th>Genre</th>
                <th>Plattform</th>
                <th>Release Date</th>
                <th>Price</th>
            </tr>
        </thead>
        <tbody>
            {games.map(games =>
                <tr key={games.g_Id}>
                    <td>{games.g_Title}</td>
                    <td>{games.g_Genre}</td>
                    <td>{games.g_Plattform}</td>
                    <td>{games.g_ReleaseDate}</td>
                    <td>{games.g_Price}</td>
                </tr>
            )}
        </tbody>
    </table>;
}

Database design:

CREATE TABLE [dbo].[Games] (
[G_Id]          INT             IDENTITY (1, 1) NOT NULL,
[G_Genre]       NVARCHAR (100)  NOT NULL,
[G_Plattform]   NVARCHAR (100)  NOT NULL,
[G_Price]       DECIMAL (18, 2) NOT NULL,
[G_ReleaseDate] DATETIME2 (7)   NOT NULL,
[G_Title]       NVARCHAR (100)  NOT NULL,
CONSTRAINT [PK_Games] PRIMARY KEY CLUSTERED ([G_Id] ASC));

I am using .Net core and MS-Sql. I have omitted the fetch method and controllers as I deemed them unnecessary for this issue, but feel free to ask for more information if needed.


What I have tried so far:

  1. Changing the datatype in the Database
  2. Attempting to convert the Date (using getyear or toDateString ...etc)
  3. Trying to format the date using moment.js
  4. Creating a new datatype that only accepts the date

Unfortunately, none of these solutions seem to work at the moment. It's possible that I am missing something obvious due to being new to React, so any guidance would be appreciated :)

Answer №1

Have you looked into any documentation regarding the Date type? Check out the Date TypeScript interface on Microsoft GitHub

Based on your question, it seems like you want to modify the date object for output purposes:

<td>{games.g_ReleaseDate}</td>

From what I've gathered, you should simply add

.toLocaleDateString()

Here's an example in TypeScript online: Visit Date TS Playground

Answer №2

If you need to format dates in your code, consider utilizing the dateformat library from the npm registry.

import * as dateFormat from 'dateformat';

const formatDate = (dt) => dateFormat(dt, "mm/dd/yyyy");


<td>{formatDate(games.g_ReleaseDate)}</td>

Alternatively, you can also achieve date formatting with the following approach.

const formatDate = (dt:Date) => dt.toLocaleDateString()

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

Tips on filtering an array in a JSON response based on certain conditions in Angular 7

Looking to extract a specific array from a JSON response based on mismatched dataIDs and parentDataIDs using TypeScript in Angular 7. { "data":[ { "dataId":"Atlanta", "parentDataId":"America" }, { "dataId":"Newyork", ...

Exploring the directories: bundles, lib, lib-esm, and iife

As some libraries/frameworks prepare the application for publishing, they create a specific folder structure within the 'dist' directory including folders such as 'bundles', 'lib', 'lib-esm', and 'iife'. T ...

Combining Axios with repeated promises

I am facing an issue with a loop in my GET request on the axis, and I cannot figure out why. const [ state, setState ] = useState<any[]>([]); ids.forEach((id) => { getData(id) .then((smth: Map<string, any>[]) => getNeededData ...

Issues with unresolved dependencies in React Native

Once I installed react-native-search-header, my app stopped compiling due to missing dependencies. Upon upgrading react native to version 0.63.4 and running npm-check on some other packages, the situation worsened. Now I find myself with numerous unresolv ...

What is the best way to retrieve the subclass name while annotating a parent method?

After creating a method decorator to log information about a class, there is a slight issue that needs addressing. Currently, the decorator logs the name of the abstract parent class instead of the effectively running class. Below is the code for the deco ...

The seamless merging of Angular2, TypeScript, npm, and gulp for enhanced development efficiency

I'm fairly new to front-end development and I am currently working on an application using Angularjs2 with TypeScript in Visual Studio 2015. I have been following the steps outlined in this Quickstart https://angular.io/docs/ts/latest/cookbook/visual- ...

Encountered an issue during the transition from Angular 7 to Angular 9

After following the advice in the second response of this discussion, I successfully upgraded to Angular 9. However, I am now encountering an issue in the browser console when running my project. Package.json "dependencies": { "@angular-devkit/build- ...

Sticky header in React data grid

Is there a way to implement a sticky header for a data grid in react? I have tried various methods but haven't been able to figure it out. Any suggestions would be appreciated. You can find my code sandbox example here. #react code export const Styl ...

Utilize Page.evaluate() to send multiple arguments

I am facing an issue with the Playwright-TS code below. I need to pass the email id dynamically to the tester method and have it inside page.evaluate, but using email:emailId in the code throws an undefined error. apiData = { name: faker.name.firstNa ...

Is there a way to adjust the starting and ending points of a bezier curve in D3 by utilizing the link generator?

I'm currently working on developing a horizontal hierarchical tree Power BI custom visual using TypeScript and D3. I am utilizing d3's treeLayout for this purpose, and my task is to create a link generator that can plot bezier, step, and diagonal ...

Differentiating elements from two array objects in typescript: a guide

I am facing an issue in extracting the different elements from two array objects. Here is my example: array1 = [{id: 1, a: "a", b: "b"}, {id: 2, c: "c", d: "d"}, {id: 3, e: "e", f: "f"}]; array2 = ...

What is the best way to change the number 123456789 to look like 123***789 using either typescript or

Is there a way to convert this scenario? I am working on a project where the userID needs to be displayed in a specific format. The first 3 characters/numbers and last 3 characters/numbers should be visible, while the middle part should be replaced with ...

Issue with npm resolution due to package requiring another third-party dependency

I'm encountering an issue with a requirement and I'm hoping for some assistance. I currently have a package called @unicoderns/orm that relies on mysql, which can be found at https://github.com/unicoderns/ORM Now I'm working on developing ...

Display a fixed three levels of highchart Sunburst upon each click in Angular8

Looking to create a dynamic sunburst highchart that displays three levels at a time while allowing interactive drilling. For instance, if there are 5 levels, the chart should initially show the first three levels. When clicking on level 3, levels 2, 3, and ...

The 'RouterLink' JSX element type is missing any construct or call signatures

While researching this issue on the internet and Stack Overflow, I've noticed a common theme with problems related to React. An example can be found here. However, I am working with Vue and encountering errors in Vue's own components within a new ...

What is the reason behind this build error I am encountering while using react-three-xr?

I'm having trouble understanding this error message. What steps can I take to resolve it? Although I have included three-xr in my react app, I am encountering the following error: Failed to compile. ../../node_modules/@react-three/xr/src/DefaultXRCon ...

The error message 'ReferenceError: MouseEvent is not defined' indicates that

Recently, I attempted to incorporate ng2-select into a project that relies on angular/universal-starter (TypeScript 2.x) as its foundation. (Interestingly, ng2-select worked perfectly fine when added to an angular-cli generated project.) However, upon ad ...

Hidden back navigation strategy in AngularJS 2 with location strategy

After creating a custom LocationStrategy to disable browser location bar changes, I am now looking to integrate smaller apps into various web pages without affecting the browser's location. While navigation works smoothly with this new strategy, I am ...

Retrieve the past week's data based on names using JavaScript

Is there a way to dynamically fetch the past seven day names, starting from today, in JavaScript? I am looking to format the result as follows: (Wednesday, Tuesday, Monday, Sunday, Saturday, Friday, Thursday, Wednesday). ...

Exploring the TypeScript Type System: Challenges with Arrays Generated and Constant Assertions

I am currently grappling with a core comprehension issue regarding TypeScript, which is highlighted in the code snippet below. I am seeking clarification on why a generated array does not function as expected and if there is a potential solution to this pr ...