【问题标题】:Coverting Date input from String format to Date format将日期输入从字符串格式转换为日期格式
【发布时间】:2016-03-01 09:44:02
【问题描述】:

我有一个注册表单,询问用户他们的开始日期。我正在使用 MEAN 框架,这意味着我在前端使用 AngularJs。

到目前为止我做了什么:

首先我尝试使用以下代码,但它不适用于 IE 和 FireFox。

<input type="date" name="startDate">

然后我尝试了在this SO question 中找到的以下正则表达式。

^(?:(?:31(\/|-|\.)(?:0?[13578]|1[02]))\1|(?:(?:29|30)(\/|-|\.)(?:0?[1,3-9]|1[0-2])\2))(?:(?:1[6-9]|[2-9]\d)?\d{2})$|^(?:29(\/|-|\.)0?2\3(?:(?:(?:1[6-9]|[2-9]\d)?(?:0[48]|[2468][048]|[13579][26])|(?:(?:16|[2468][048]|[3579][26])00))))$|^(?:0?[1-9]|1\d|2[0-8])(\/|-|\.)(?:(?:0?[1-9])|(?:1[0-2]))\4(?:(?:1[6-9]|[2-9]\d)?\d{2})$

完美的作品。下面是它在我的应用中如何工作的图片。

问题:

当用户提交表单时,数据将保存在 MongoDB 中。在上图中,您可以看到数据保存为字符串。我想将其转换为正确的日期格式,以便在服务器端 (Node.js) 上执行操作,即过滤所有在 2015 年之后开始或在 1999 年和 2001 年之间离开的用户等。

任何建议都会有所帮助。

更新:

目前我正在测试 moment.js。有结果后会更新我的问题。

结果:

我使用 moment.js 尝试了以下操作:

console.log("MOMENT" + moment("1993-03-25").format());

以下输出是:

MOMENT 1993-03-25T00:00:00+00:00

我不确定这是否是保存在 MongoDB 中的正确格式,是否允许我对其执行服务器端操作。

【问题讨论】:

  • 这是来自 mongo 文档Internally, Date objects are stored as a 64 bit integer representing the number of milliseconds since the Unix epoch (Jan 1, 1970), which results in a representable date range of about 290 millions years into the past and future.

标签: javascript angularjs node.js mongodb date


【解决方案1】:

您需要将 moment 对象转换为 JavaScript 日期,然后才能将其在 MongoDB 中保存为日期字段:

moment("1993-03-25").toDate()

【讨论】:

  • 非常感谢您的回答。上面的代码输出以下格式Thu Mar 25 1993 00:00:00 GMT+0000 (GMT)。这是要保存的正确格式吗?
  • 是的,这是正确的格式。它实际上是一个 JavaScript 日期对象,然而,Mongo 知道如何处理这些。
猜你喜欢
  • 2013-12-28
  • 2016-06-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-02-23
  • 1970-01-01
  • 2020-11-20
相关资源
最近更新 更多