【问题标题】:Printing date without time打印没有时间的日期
【发布时间】:2021-04-27 12:08:19
【问题描述】:

我还是 react(Typescript) 的新手,我想打印一个从数据库中得到但没有时间的日期。

这是我的界面:

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

和我的输出方法:

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>;
}

以及数据库设计

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));

我正在使用 .Net core 和 MS-Sql(我没有添加 fetch 方法和控制器,因为我认为它们并不重要,所以请随时询问是否重要)。


到目前为止我尝试过的是:

  1. 更改数据库中的数据类型
  2. 尝试转换日期(使用 getyear 或 toDateString ...等)
  3. 我尝试使用 moment 更改格式
  4. 创建只接受日期的新日期类型

到目前为止似乎没有任何效果(可能是因为我是新手,所以我遗漏了一些明显的东西,对此感到抱歉:))

【问题讨论】:

    标签: sql-server typescript react-native date


    【解决方案1】:

    您可以为此使用dateformat npm package。

    import * as dateFormat from 'dateformat';
    
    const formatDate = (dt) => dateFormat(dt, "mm/dd/yyyy");
    
    
    <td>{formatDate(games.g_ReleaseDate)}</td>
    

    或者你可以试试这个。

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

    【讨论】:

    • 谢谢它工作得很好! p.s:在打字稿中,我必须像这样导入它 `import * as dateFormat from 'dateformat'; ` .
    【解决方案2】:

    您是否检查过有关日期类型的任何文档? Date TypeScript interface on microsoft github

    从我从您的问题中了解到,您想出于输出原因修改日期对象:

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

    从我发现你应该只需要添加

    .toLocaleDateString()
    

    在线TS示例:Date TS Playground

    【讨论】:

    • 我确实阅读了有关日期类型的信息,问题是每当我尝试使用类似“games.g_ReleaseDate.toLocaleDateString()”的东西时,我都会收到一条错误消息,说它不允许成为一个函数,它即使我尝试定义一个新的变量“new Date().toDateString()”也不起作用,这就是我感到困惑的原因,尽管我在过去一个小时左右谷歌搜索
    猜你喜欢
    • 2023-03-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-06-26
    • 2017-11-02
    • 2012-04-09
    • 1970-01-01
    相关资源
    最近更新 更多