Paw*_*lov 5 javascript timezone mongodb
我正在 Mongo db 中运行 map reduce 作业。
映射函数应该将某种性质的事件映射(例如计数)到某个时区的天(映射的关键是日历日)。时区可以不同,实际上是 map/reduce 作业的输入参数。
存储在数据库对象中的时间是 UTC。
例子:
object1: time=78000
object2: time=86420
mapReduce(objects, tz='America/Los_Angeles')
would return: [{"1/1/1970" : 2}]
Run Code Online (Sandbox Code Playgroud)
和
mapReduce(objects, tz='Europe/London')
would return: [{"1/1/1970":1},{"1/2/1970":1}]
Run Code Online (Sandbox Code Playgroud)
在同一个数据集上。
JavaScript Date 对象可以完美地将任何 UTC 时间转换为本地时间,但它似乎仅限于 J/S 环境的“当前”时区。我似乎找不到一种方法来指定我希望转换所在的时区。
转换应考虑 DST,最好考虑闰秒。
我能做些什么来实现这一目标吗?
I found the answer that will work for me. The scope, after all, was limited to having this support in server-side mongo DB, and only on Linux.
@AsyaKamsky pointed to a greate J/S library, timezone-js, that does full and proper time zone support, considering that it uses actual time zone files from IANA. However, loading arbitrary java-script libraries into Mongo server environment is not that easy. You can only load global function definitions. timezone-js also needs to be provided with a custom transport mechanism to download the timezone files (I don't even know if MongoDB server environment provides files access), or the time zone files have to be precompiled into JSON objects, and served along with the library. I decided that this would be too tedious of an approach, and I will have to be responsible of providing mechanism to update time zone files when they are changed.
我正在研究的另一个替代方案是破解 Mongo 中使用的 J/S 实现,以添加一个函数来完成我想要它做的工作。这就是我所做的。在 glibc 的世界里,事情实际上和在 JavaScript 中一样令人沮丧,但是有一个库可以完成这项工作,icu。
我制作了这个补丁,它添加了一个静态 Date.daytz() 函数,该函数采用 UTC 时间戳和时区名称,将返回一个 yyyy-mm-dd 字符串。
考虑以下 map/reduce 函数:
fmap = function () {
emit(Date.daytz(this.time * 1000, globtz), {count:1});
};
fred = function (k, v) {
var r = {count:0};
v.forEach(function (v0) {r.count += v0.count;});
return r;
};
Run Code Online (Sandbox Code Playgroud)
我得到了我想要的,运行这两个 map reduce 命令:
{ "mapreduce" : "objects",
"map" : fmap,
"reduce" : fred,
"out" : { "inline" : 1 },
"scope" : { "globtz" : "Europe/London" } }
Run Code Online (Sandbox Code Playgroud)
和
{ "mapreduce" : "objects",
"map" : fmap,
"reduce" : fred,
"out" : { "inline" : 1 },
"scope" : { "globtz" : "America/Los_Angeles" } }
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
2468 次 |
最近记录: |