On this page本页内容
$dateToString
Converts a date object to a string according to a user-specified format.根据用户指定的格式将日期对象转换为字符串。
The $dateToString expression has the following operator expression syntax:$dateToString表达式具有以下运算符表达式语法:
{ $dateToString: {
date: <dateExpression>,
format: <formatString>,
timezone: <tzExpression>,
onNull: <expression>
} }
The $dateToString takes a document with the following fields:$dateToString获取具有以下字段的文档:
date |
| ||||||
format |
format field is optional if featureCompatibilityVersion (fCV) is set to "4.0" or greater. featureCompatibilityVersion(fCV)设置为“4.0”或更高,则format字段是可选的。setFeatureCompatibilityVersion.setFeatureCompatibilityVersion。
| ||||||
timezone |
| ||||||
onNull |
|
The following format specifiers are available for use in the 以下格式说明符可用于<formatString>:<formatString>:
%d | 01-31 | |
%G | 0000-9999 | |
%H | 00-23 | |
%j | 001-366 | |
%L | 000-999 | |
%m | 01-12 | |
%M | 00-59 | |
%S | 00-60 | |
%w | 1-7 | |
%u | 1-7 | |
%U | 00-53 | |
%V | 01-53 | |
%Y | 0000-9999 | |
%z | +/-[hh][mm] | |
%Z | +/-[hhmm]) was +0445, the minutes offset is +285.+/-[hhmm])为+0445,则分钟偏移量为+285。
| +/-mmm |
%% | % |
Consider a 考虑具有以下文档的sales collection with the following document:sales集合:
{
"_id" : 1,
"item" : "abc",
"price" : 10,
"quantity" : 2,
"date" : ISODate("2014-01-01T08:15:39.736Z")
}
The following aggregation uses 以下聚合使用$dateToString to return the date field as formatted strings:$dateToString以格式化字符串的形式返回date字段:
db.sales.aggregate(
[
{
$project: {
yearMonthDayUTC: { $dateToString: { format: "%Y-%m-%d", date: "$date" } },
timewithOffsetNY: { $dateToString: { format: "%H:%M:%S:%L%z", date: "$date", timezone: "America/New_York"} },
timewithOffset430: { $dateToString: { format: "%H:%M:%S:%L%z", date: "$date", timezone: "+04:30" } },
minutesOffsetNY: { $dateToString: { format: "%Z", date: "$date", timezone: "America/New_York" } },
minutesOffset430: { $dateToString: { format: "%Z", date: "$date", timezone: "+04:30" } }
}
}
]
)
The operation returns the following result:该操作返回以下结果:
{
"_id" : 1,
"yearMonthDayUTC" : "2014-01-01",
"timewithOffsetNY" : "03:15:39:736-0500",
"timewithOffset430" : "12:45:39:736+0430",
"minutesOffsetNY" : "-300",
"minutesOffset430" : "270"
}