Inserting a Date in a MongoDB Document from Java - mongodb-java

I'm inserting a Date in a MongoDB key from Java as follows:
DateFormat formatter = new SimpleDateFormat("dd-MMM-yyyy");
Date date = (Date)formatter.parse("1-Apr-1970");
BasicDBObject doc = new BasicDBObject("name", "john").append("birthdate", date);
Querying for the Document, it results the following Date:
{ "_id" : { "$oid" : "55263cd3d3d584440534f0a4"} , "name" : "john" ,
"birthdate" : { "$date" : "1970-03-31T23:00:00.000Z"}}
As you can see, the month is not what I expected (04). Is there a better way to insert a Date in MongoDB from Java ? as it is, I find it pretty useless when I try to read it back from Java (I'd rather use a plain key String).

This happens because of the implementation of toString() method in BasicDbObject. By default dates are printed like that:
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");
format.setCalendar(new GregorianCalendar(new SimpleTimeZone(0, "GMT")));
So you have time for GMT time zone. If you try to get date filed (e.g.: dbObject.get("birthdate")) you should be able to see expected value.

Related

Elastic search update-by-query how work with date field (parse from string?)

I'm new in elastic and I need work with date in update-by-query script.
I have docs with field expire which is mapped as date.
I try in my script in update-by-query:
SimpleDateFormat expire = new SimpleDateFormat(\"yyyy-MM-dd'T'HH:mm:ss Z\", Locale.getDefault());
long expireTime = expire.parse(ctx._source.expire).getTime();
But there is error: Unparseable date: "2017-07-21T11:19:42+02:00"
Is there a different way, how got date object or UNIX timestamp?
Or is there a way how got mapped formats instead of strings in update-by-query?
Thank you.
There's some documentation on working with dates in scripts. Just do this and it will work:
long expireTime = ZonedDateTime.parse(ctx._source.expire).toInstant().toEpochMilli()

How to get Current date using Poco ? (Only Date) No Time Stamp

Is there a way we get a Date only from Poco ? One way is to get the Poco DateTime stamp and truncate the Date, But is there any way which gives directly current Date ?
Like for example I am using like this to get Date
void getTimestamp(std::string &out_iTimestamp)
{
//Get the CurrentTimestamp
Poco::Timestamp t_oCurTimestamp;
Poco::DateTimeFormatter t_oFormatter;
string t_strDateTime;
t_oFormatter.append(t_strDateTime, t_oCurTimestamp, Poco::DateTimeFormat::ISO8601_FORMAT);
out_iTimestamp = t_strDateTime;
}
Now I am truncating the Date
std::string t_strDateTime;
std::string t_strDate;
getTimestamp(t_strDateTime);
//extract the only Date from DateTimeStamp
std::size_t found = t_strDateTime.find('T');
if (found != std::string::npos){
t_strDate = t_strDateTime.substr(0,found);
}
Any one know the simple way ?
As already answered here, use Poco::DateTimeFormatter with your own format:
Poco::DateTimeFormatter::format(date, "%d/%m/%Y");

How can i change timezone in neo4j?

I want to change default timezone from UTC to another timezone. How it will be possible? I tried
RETURN apoc.date.format(timestamp(),'ms', 'yyyy/MM/dd HH/mm/ss')
but it returns utc time on localhost.
Example answer:
RETURN apoc.date.format(timestamp(),'ms', 'yyyy/MM/dd HH:mm:ss',"Europe/Paris")
Method from the source:
public String format(final
#Name("time") Long time
,#Name(value = "unit", defaultValue = "ms") String unit
,#Name(value = "format",defaultValue = DEFAULT_FORMAT) String format
,#Name(value = "timezone",defaultValue = "") String timezone)
{
return time == null ? null : parse(unit(unit).toMillis(time), format, timezone);
}
The timezone parameter is further passed to Java TimeZone class constructor.
From Java documentation as to what it should contain -
the ID for a TimeZone, either an abbreviation such as "PST", a full
name such as "America/Los_Angeles", or a custom ID such as "GMT-8:00".
Note that the support of abbreviations is for JDK 1.1.x compatibility
only and full names should be used.
The source code of this project -
https://github.com/neo4j-contrib/neo4j-apoc-procedures/blob/3.3/src/main/java/apoc/date/Date.java
For more info, have a look at this article about dates in APOC
http://xclave.azurewebsites.net/2018/02/28/better-know-apoc-apoc-3-date-parse-format/

Laravel 5: can't set date from string

On my db migration i have a "dob" field:
$table->date('DOB')->nullable();
I have a string representing a date: "12/12/1960" in the input. I tested "dob" and the content is there. But when I try to set it to the "dob" field in the database..
$member->DOB = date('m/d/Y',Request::input('dob'));
The datebase field becomes 0000-00-00
What am I doing wrong?
The database most likely wants it in YYYY-MM-DD format. So just changing the format should work. But to get from 12/12/1960 to there, you need to parse it.
$oldDateString = '12/12/1960';
$newDateString = DateTime::createFromFormat('m/d/Y', $oldDateString)->format('Y-m-d');
Look at definition
string date ( string format [, int timestamp] )
Second parameter is timestamp, not string
Use DateTime PHP5 functions or Laravel Carbon
E.g. date_create_from_format('m/d/Y', Request::input('dob'))
->format('Y-m-d H:i:s');

How do I extract the created date out of a Mongo ObjectID

I'm using the Mongo shell to query my Mongo db. I want to use the timestamp contained in the ObjectID as part of my query and also as a column to extract into output. I have setup Mongo to create ObjectIDs on its own.
My problem is I can not find out how to work with the ObjectID to extract its timestamp.
Here are the queries I am trying to get working. The 'createdDate' field is a placeholder; not sure what the correct field is:
//Find everything created since 1/1/2011
db.myCollection.find({date: {$gt: new Date(2011,1,1)}});
//Find everything and return their createdDates
db.myCollection.find({},{createdDate:1});
getTimestamp()
The function you need is this one, it's included for you already in the shell:
ObjectId.prototype.getTimestamp = function() {
return new Date(parseInt(this.toString().slice(0,8), 16)*1000);
}
References
Check out this section from the docs:
Extract insertion times from _id rather than having a separate timestamp field
This unit test also demostrates the same:
mongo / jstests / objid6.js
Example using the Mongo shell:
> db.col.insert( { name: "Foo" } );
> var doc = db.col.findOne( { name: "Foo" } );
> var timestamp = doc._id.getTimestamp();
> print(timestamp);
Wed Sep 07 2011 18:37:37 GMT+1000 (AUS Eastern Standard Time)
> printjson(timestamp);
ISODate("2011-09-07T08:37:37Z")
This question is helpful to understand of how to use the _id's embedded timestamp in query situations (refers to the Mongo Extended JSON documentation). This is how it's done:
col.find({...,
'_id' : {'$lt' : {'$oid' : '50314b8e9bcf000000000000'}}
})
finds documents created earlier than the one that's given by oid. Used together with natural sorting and limiting you can utilize BSON _ids to create Twitter-like API queries (give me the last OID you have and I'll provide twenty more)
In python you can do this:
>>> from bson.objectid import ObjectId
>>> gen_time = datetime.datetime(2010, 1, 1)
>>> dummy_id = ObjectId.from_datetime(gen_time)
>>> result = collection.find({"_id": {"$lt": dummy_id}})
I think, ObjectId.from_datetime() - its a useful method of standard bson lib
Maybe other language bindings have alternative builtin function.
Source: http://api.mongodb.org/python/current/api/bson/objectid.html
To use the timestamp contained in the ObjectId and return documents created after a certain date, you can use $where with a function.
e.g.
db.yourcollection.find( {
$where: function() {
return this._id.getTimestamp() > new Date("2020-10-01")
}
});
The function needs to return a truthy value for that document to be included in the results. Reference: $where
Mongo date objects can seem a bit peculiar though. See the mongo Date() documentation for constructor details.
excerpt:
You can specify a particular date by passing an ISO-8601 date string with a year within the inclusive range 0 through 9999 to the new Date() constructor or the ISODate() function. These functions accept the following formats:
new Date("<YYYY-mm-dd>") returns the ISODate with the specified date.
new Date("<YYYY-mm-ddTHH:MM:ss>") specifies the datetime in the client’s local timezone and returns the ISODate with the specified datetime in UTC.
new Date("<YYYY-mm-ddTHH:MM:ssZ>") specifies the datetime in UTC and returns the ISODate with the specified datetime in UTC.
new Date(<integer>) specifies the datetime as milliseconds since the Unix epoch (Jan 1, 1970), and returns the resulting ISODate instance.

Resources