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

Generics in Typescript implemented for a React component that accepts an array of records along with an array of

I am currently working on developing a straightforward typed react component designed to display a table from an array of objects. The input data is structured as follows: // array of records containing data to render in the table data = [ { one: 1, ...

Looking into time zones that do not observe daylight saving time

My code successfully converts timezones to GMT/UTC and vice-versa. However, I am looking to enhance its functionality by checking for non-DST timezones and allowing for dates/times in any format. For example, if only a date is provided, the correct result ...

How to create a collapse feature that allows only one item to be open at a time in Angular

I developed an angular app with a collapse feature, but I noticed that multiple collapses can be open at once. I am utilizing Ng-Bootstrap collapse for this functionality. Below is the code snippet from the TS file: public isCollapsed = true; And here is ...

Transferring data from two child components back to the parent component

Within my web application, I have a parent component (A) and two children components (B, C). The parent component is responsible for maintaining the basic layout of the page, which remains consistent across all layouts. However, I need to dynamically swap ...

What is the best way to enable the acceptance of a null value during the validation process of an optional

Currently, I am in the process of assembling a sandwich. Whenever all the necessary details are provided to Nest, everything operates smoothly and flawlessly. However, my predicament arises when attempting to assign null (empty string) to an enum, resultin ...

Tips for locating the index of a substring within a string with varying line endings using Typescript

I am faced with the task of comparing two strings together. abc\r\ndef c\nde My goal is to determine the index of string 2 within string 1. Using the indexOf() method is not an option due to different line endings, so I require an altern ...

Strange behavior when working with Typescript decorators and Object.defineProperty

I'm currently working on a project that involves creating a decorator to override a property and define a hidden property. Let's take a look at the following example: function customDecorator() { return (target: any, key: string) => { ...

Executing Timers in Angular 5 Service

I am working on implementing a property called currentAndLastVehicles in my service that needs to be updated automatically every second. Here is what I have so far: import { Injectable } from '@angular/core'; @Injectable() export class SharedD ...

Managing database downtime with TypeORM

In the event that my MSSQL server experiences a crash and an app client makes a request to the API, the current behavior is for it to endlessly spin until Express times out the unanswered request. By enabling logging in TypeORM, I am able to observe the e ...

Experiencing issues with the functionality of getServerSideProps in my project

I'm scratching my head over why server-side props aren't working for me in nextjs (v12). I'm utilizing getServerSideProps inside pages/details/index.tsx. export const getServerSideProps = async (context: any) => { const name = context.q ...

Setting a custom tab as the default route in Expo Router without relying on an index.tsx file - here's how!

In the development of my React Native app using Expo Router, I am structuring it into main sections with a tabs layout consisting of Events, Search, and Profile. Here is an image showcasing the desired folder structure: The main sections Events, Search, ...

Troubleshooting: Unable to Open Page with Google Material Button in Angular 5

Currently, I'm facing an issue with a button that is not opening to a new site despite following what seems like simple steps. <button mat-raised-button href="https://www.google.com/" color="primary">Connect with Stripe</button> I even a ...

Configuring Jest with TypeScript: A guide to setting up and running tests across multiple files

Currently, I am diving into the world of TDD and attempting to create a basic test suite for my Node Express API. My project directory has the following structure: . └── root/ ├── src/ │ ├── services/ │ │ └─ ...

The insertion of decimal values in SQL Server is not functioning properly

When it comes to saving decimal values with up to 14 digits precision using Decimal(20,14), there seems to be an issue. If the inserted value has fewer precision digits, instead of simply adding zeros, the missing digits are filled in randomly. For instanc ...

Is it possible to transform a Next.js application into a React Native mobile app?

I've been really enjoying using Next.js in combination with tailwindcss for my web app. Now I want to expand its reach by creating iOS and Android versions, but I'm not sure if I can simply convert my existing Next.js project into a mobile app or ...

Are reflection problems a concern when using type-graphql mutations?

Recently, I've been experimenting with integrating type-graphql into my nodejs project. While implementing @Query methods went smoothly, I'm facing challenges with the following code snippet in combination with Moleculer service. @Mutation() / ...

Tips for updating the pagination layout in Material UI Table

Currently, I am attempting to modify the background color of the list that displays the number of rows in MUI TablePagination. <TablePagination style={{ color: "#b5b8c4", fontSize: "14px" }} classes={{selectIcon: ...

Typescript navigation and Next.js technology

Currently, I am in the process of learning typescript and attempting to create a navigation bar. However, I encountered an error message stating "Unexpected token header. Expected jsx identifier". I am a bit puzzled by this issue. Could someone kindly pro ...

Anticipate receiving a 'Type' returned by external library functions

I've recently started learning TypeScript and have encountered a situation where I need to assign a type to a variable that is returned from a third-party library function with its own type definition. For instance: import {omit} from 'lodash&ap ...

Is the `getUniqueId()` function from react-native-device-info returning a UUID or a GUID?

When working on my React Native app, I encountered the need to provide a unique ID to an API endpoint. I was informed that it had to be in GUID format. This raised a couple of questions for me: 1) Is the getUniqueId() method from the react-native-device-i ...