vikasse
vikasse

Reputation: 455

MongoDB DateTime Format

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

Upvotes: 1

Views: 40382

Answers (5)

Sandun Susantha
Sandun Susantha

Reputation: 1140

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.

  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]

Upvotes: 1

WesternGun
WesternGun

Reputation: 12728

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

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..

Upvotes: 0

vikasse
vikasse

Reputation: 455

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

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.

Upvotes: 3

Marc
Marc

Reputation: 5548

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

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

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

The Java documentation on the Date object may be found here: http://docs.oracle.com/javase/1.4.2/docs/api/java/util/Date.html As 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)."

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

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

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!

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

Upvotes: 2

SomethingOn
SomethingOn

Reputation: 10881

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?

Upvotes: 2

Related Questions