如何格式化来自MongoDB的日期? [英] How can I format a date coming from MongoDB?

查看:1088
本文介绍了如何格式化来自MongoDB的日期?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用Jade从Express.js中呈现我的视图.我将文档保存在MongoDB中,并使用Mongoose访问我的文档.我正在保存创建新文档时创建的默认日期,并将该创建日期属性返回到需要格式化的视图.在MongoDB中存储的日期的格式为:

I'm using Jade to render my views from within Express.js. I am saving documents in MongoDB and using Mongoose to access my documents. I am saving a default date created when a new document is created and I am returning that date created attribute to the view, where is needs to be formatted. The format of the date being stored within MongoDB is:

Thu Dec 29 2011 20:14:56 GMT-0600 (CST)

我的问题是:如何格式化从MongoDB返回的Jade(或Mongoose或Node.JS)中的日期?

推荐答案

JavaScript内置了对日期的支持.首先,将您的字符串放入Date对象中:

JavaScript has built-in support for dates. First, to get your string into a Date object:

date =  new Date('Thu Dec 29 2011 20:14:56 GMT-0600 (CST)')

现在您可以在日期上使用各种方法来获取所需的数据:

Now you can use various methods on the date to get the data you need:

date.toDateString() // "Thu Dec 29 2011"
date.toUTCString()  // "Fri, 30 Dec 2011 02:14:56 GMT"
date.getMonth()     // 11
date.getDate()      // 29
date.getFullYear()  // 2011

您可以在MDN参考网站上看到更多方法.您可以使用这些方法来构建所需的任何类型的字符串.

You can see more methods on the MDN reference site. You can use these methods to build any kind of string you want.

要获得更可靠的日期/时间解析,格式设置和操作,您一定应该查看 Moment.js s3v3n在另一个答案中.

For more robust date/time parsing, formatting, and manipulation, you should definitely check out Moment.js as mentioned by s3v3n in another answer.

这篇关于如何格式化来自MongoDB的日期?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆