MongoDB 日期时间格式

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9944694/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-09 12:35:05  来源:igfitidea点击:

MongoDB DateTime Format

mongodb

提问by vikasse

In mongodb adhoc query, before executing the query, how to format the date type element to dd\mm\yyyyformat and then execute the query?

在mongodb即席查询中,在执行查询之前,如何将日期类型元素dd\mm\yyyy格式化为格式化后再执行查询?

回答by vikasse

I solved this by inserting the datetime as integer using the getTime() method in java. EG:

我通过使用 java 中的 getTime() 方法将日期时间作为整数插入来解决这个问题。例如:

Date dt=new Date();
long integer_date=dt.getTime();

I used the above line of code to insert date as integer.With this it was easy to fetch records between a particular date.

我使用上面的代码行将日期作为整数插入。这样可以很容易地获取特定日期之间的记录。

回答by SomethingOn

I asked a similar question a little while back...this might be what you're looking for: What is the syntax for Dates in MongoDB running on MongoLab?

不久前我问了一个类似的问题……这可能就是你要找的:在 MongoLab 上运行的 MongoDB 中日期的语法是什么?

回答by Marc

If you are using Java, you can create Date objects from strings using the parse method of the DateFormat class.

如果您使用的是 Java,则可以使用 DateFormat 类的 parse 方法从字符串创建 Date 对象。

The Java documentation on the DateFormat Class may be found here: http://docs.oracle.com/javase/1.4.2/docs/api/java/text/DateFormat.html

关于 DateFormat 类的 Java 文档可以在这里找到:http: //docs.oracle.com/javase/1.4.2/docs/api/java/text/DateFormat.html

The specific section on the parse method is here: http://docs.oracle.com/javase/1.4.2/docs/api/java/text/DateFormat.html#parse%28java.lang.String%29

解析方法的具体部分在这里:http: //docs.oracle.com/javase/1.4.2/docs/api/java/text/DateFormat.html#parse%28java.lang.String%29

The Java documentation on the Date object may be found here: http://docs.oracle.com/javase/1.4.2/docs/api/java/util/Date.htmlAs per the "Constructor Summary" section, the ability to pass a string into the constructor is "Deprecated. As of JDK version 1.1, replaced by DateFormat.parse(String s)."

可以在此处找到有关 Date 对象的 Java 文档:http: //docs.oracle.com/javase/1.4.2/docs/api/java/util/Date.html根据“构造函数摘要”部分,能力将字符串传递给构造函数是“不推荐使用的。从 JDK 1.1 版开始,由 DateFormat.parse(String s) 替换。”

While I was researching the above, I also came across the Calendar class, which may be used for converting a Date object and a set of integers. It may not be necessary for this application, but I thought it might be useful to include a link to the documentation: http://docs.oracle.com/javase/1.4.2/docs/api/java/util/Calendar.html

在研究上述内容时,我还遇到了 Calendar 类,该类可用于转换 Date 对象和一组整数。此应用程序可能不需要它,但我认为包含指向文档的链接可能很有用:http: //docs.oracle.com/javase/1.4.2/docs/api/java/util/Calendar。 html

Integers for year, month, day, hour, etcetera may be passed in via the set method: http://docs.oracle.com/javase/1.4.2/docs/api/java/util/Calendar.html#set%28int,%20int,%20int,%20int,%20int%29

年、月、日、小时等的整数可以通过 set 方法传入:http: //docs.oracle.com/javase/1.4.2/docs/api/java/util/Calendar.html#set% 28int,%20int,%20int,%20int,%20int%29

By way of example, here is a short Java Program that creates a number of Date objects, stores them in a Mongo collection, and then executes a query similar to what you have described. Hopefully it will help you to accomplish your goal. NOTE: This program drops a collection named "dates", so be sure to change the collection name if you already have such a collection in your database!

举例来说,这里有一个简短的 Java 程序,它创建多个 Date 对象,将它们存储在 Mongo 集合中,然后执行类似于您所描述的查询。希望它能帮助你实现你的目标。注意:这个程序会删除一个名为“dates”的集合,所以如果您的数据库中已经有这样的集合,请务必更改集合名称!

public static void main(String[] args) throws UnknownHostException, MongoException {
    Mongo m = new Mongo( "localhost:27017" );
    DB db = m.getDB("test");

    DBCollection coll = db.getCollection("dates");
    coll.drop();

    DateFormat df = DateFormat.getInstance();
    String dateString = new String();
    Date myDate = new Date();
    // Save some test documents
    for(int i=1; i<11; i++){
        dateString = "04/" + String.valueOf(i) + "/12 11:00 AM, EST";
        BasicDBObject myObj = new BasicDBObject("_id", i);
        try {
            myDate = df.parse(dateString);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        myObj.put("date", myDate);
        System.out.println(myDate);
        coll.save(myObj);
    }

    // Build the query 
    Date startDate = new Date();
    Date endDate = new Date();
    try {
        startDate = df.parse("04/4/12 11:00 AM, EST");
        endDate = df.parse("04/6/12 11:00 AM, EST");
    } catch (ParseException e) {
        e.printStackTrace();
    }
    BasicDBObject dateQuery = new BasicDBObject();
    dateQuery.put("$gte", startDate);
    dateQuery.put("$lte", endDate);

    System.out.println("---------------");
    //Execute the query
    DBCursor myCursor  = coll.find(new BasicDBObject("date", dateQuery));

    //Print the results
    while(myCursor.hasNext()){
        System.out.println(myCursor.next().toString());
    }
}

回答by Sandun Susantha

This is use full to format code to date format from simple date time format and the reverse steps also supporting this way to retrieve date from MongoDB.

这是使用 full 将代码从简单的日期时间格式格式化为日期格式,反向步骤也支持这种从 MongoDB 检索日期的方式。

  SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
  Date fDate = formatter.parse((String) metaData.getValue());
  newMeta.setValue(fDate);[![In this image you can see how is the save scenario process in mongoDB][1]][1]

回答by WesternGun

Dateclass has a before(date)or after(date)method... It is easy to use: no conversion to seconds/milliseconds.

Date类有一个before(date)orafter(date)方法...它易于使用:无需转换为秒/毫秒。

public void execute(Tuple input) {
    try {
        date=(Date) input.getValueByField("date");
        boolean before = date.before(myDate); // compare the data retrieved with your date.
        if (before) {
            ...
        } else {
            ...
        }
    } catch (Exception e) {
        logger.error("Error...", e);
    }

This approach is easier than the accepted answer..

这种方法比公认的答案更容易..