【问题标题】:Format JS datetime to correct ISO format将 JS 日期时间格式化为更正 ISO 格式
【发布时间】:2019-09-05 03:23:51
【问题描述】:

几天来,我一直在尝试让我的服务器端代码 (C#) 保存通过 API 调用发送到 Postgres 的时间戳。

如果我将DateTime.Now() 附加到数据传输对象,它似乎工作正常,但是当我尝试解析从客户端发送的日期时间时,我得到一个 400

**0: "The input was not valid."**. 

作为我的回应。

我的课是这样的

TS:

export interface ArtistShows {
    showDate: string;
    venue: string;
    id?: string;
    bandsAlsoPlaying: Array<string>;
}

C#

public class ArtistShow
{
    public Guid Id { get; set; }
    public DateTime ShowDate { get; set; }
    public string Venue { get; set; }
    public string BandsAlsoPlaying { get; set; }

    public virtual Artist Artist { get; set; }
}

映射新表单的方法(带输出日期)(TS)

private _mapNewShowForm(): ArtistShows {
    let showDate = this.newShowForm.get(this.newShowFormEnum.DATE).value;
    let convertedShowDate = new Date(showDate);

    return {
      bandsAlsoPlaying: [],
      showDate: convertedShowDate.toISOString(),
      venue: `${this.newShowForm.get(this.newShowFormEnum.VENUE).value}, ${this.newShowForm.get(this.newShowFormEnum.CITY).value}`
    };
}

请求的日期格式:“2019-01-04T00:00:00.000Z” 所需格式:“2018-12-29 20:23:22.667766”

我的问题是,有谁知道我应该以什么格式将日期发送到后端(我听说它是​​ ISO 8601)?我什至应该对客户端上的日期做任何事情吗?以及如何将我的 JS 日期转换为将保存在 PG 中的日期?

我还在使用带有 Postgres 的 Microsoft Entity Framework Core(如果有帮助的话)

【问题讨论】:

标签: angular postgresql typescript asp.net-core entity-framework-core


【解决方案1】:

使用 unix_timestamp 作为基本格式,根据需要进行转换

在 c# 中获取 unix 时间戳:

var timestamp = new DateTimeOffset(DateTime.Now).ToUnixTimeSeconds();

从 c# 中的 unix 时间戳获取日期时间:

DateTime dt = DateTimeOffset.FromUnixTimeSeconds(1549741828).DateTime;

在 javascript 中获取 unix 时间戳:

let timestamp = parseInt(new Date().getTime()/1000);

从 c# 中的 unix 时间戳获取日期时间:

let date = new Date(1549742450 * 1000)

【讨论】:

    【解决方案2】:

    所以我真的忘记了我已经打开了这个问题。 6个月后我再次询问,得到了我想要的答案:

    Parse JS Date.toIsoString in C#

    最后答案只是使用Convert.ToDateTime(),它给了我所需的确切日期格式。

    结束这个问题!

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-01-03
      • 1970-01-01
      • 1970-01-01
      • 2018-04-01
      • 2022-06-27
      • 1970-01-01
      相关资源
      最近更新 更多