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/
Related
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 you make LocalDate to return Date in a specific format ?
Ex . LocalDate ld = LocalDate.now();
The above statement will return date like 2018-11-24 but i want it to return like 24-11-2018 .
** Dont say use formatter because formatter will not return date , it will return String which is of no use for me .
Your question is contradictory, for example you want "24-11-2018" but also want "date" instead of "String" and overlook the fact that "24-11-2018" is a date in string form. A date will never have only one accepted format. So yes, for representing a date as string, users should apply any customized formatter.
But I suspect that you want to change the behaviour of the LocalDate-method toString() which produces a string in the ISO-format "2018-11-24". Well, you cannot because the class LocalDate is final so overriding this method is impossible, and there is also no configuration hook to change the behaviour because this would be in conflict with the immutability of the class.
I am using the ZonedDateTime with DateTimeFormatter of Java 8. When I try to parse my own pattern it doesn't recognizes and throws an exception.
String oraceDt = "1970-01-01 00:00:00.0";
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.S");
ZonedDateTime dt = ZonedDateTime.parse(oraceDt, formatter);
Exception in thread "main" java.time.format.DateTimeParseException: Text '1970-01-01 00:00:00.0' could not be parsed: Unable to obtain ZonedDateTime from TemporalAccessor: {},ISO resolved to 1970-01-01T00:00 of type java.time.format.Parsed
at java.time.format.DateTimeFormatter.createError(DateTimeFormatter.java:1918)
at java.time.format.DateTimeFormatter.parse(DateTimeFormatter.java:1853)
at java.time.ZonedDateTime.parse(ZonedDateTime.java:597)
at com.timezone.Java8DsteTimes.testZonedDateTime(Java8DsteTimes.java:31)
at com.timezone.Java8DsteTimes.main(Java8DsteTimes.java:11)
Caused by: java.time.DateTimeException: Unable to obtain ZonedDateTime from TemporalAccessor: {},ISO resolved to 1970-01-01T00:00 of type java.time.format.Parsed
Well, you want to create a ZonedDateTime which always refers to a timezone but your input does not contain such an information, and you have also not instructed your formatter to use a default timezone if the input is missing a zone. There are two solutions for your problem:
Instruct your parser to use a timezone (here using the system tz as example):
String oraceDt = "1970-01-01 00:00:00.0";
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.S");
ZonedDateTime zdt =
ZonedDateTime.parse(oraceDt, formatter.withZone(ZoneId.systemDefault()));
System.out.println(zdt); // in my default zone => 1970-01-01T00:00+01:00[Europe/Berlin]
Use another result type which does not need a timezone (here LocalDateTime):
String oraceDt = "1970-01-01 00:00:00.0";
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.S");
LocalDateTime ldt = LocalDateTime.parse(oraceDt, formatter);
System.out.println(ldt); // 1970-01-01T00:00
Here is an small example of using the ZonedDateTime with DateTimeFormatter of Java 8.
public String currentDateTime() {
DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("EEEE y-MM-d MMMM HH:m:s z Z'['VV']' 'Day:'D");
return ZonedDateTime.now(ZoneId.of("Europe/Lisbon")).format(dateTimeFormatter);
}
The ZonedDateTime class permits you to create a date/time object with a time zone. The default time zone will be used; i.e., the time zone you have established on your computer. You can use the DateTimeFormatter class to display the time zone. In the Java code, the time zone is displayed as zone offset, zone name and zone ID. Note that the date time formatter pattern is "Z", "z", and "VV", respectively. The program also creates a date/time object and then adds the zone ID using the of method of the ZoneId class. Finally, a time zone is added to another date/time object using the of method of the ZoneOffset class.
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');
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.