使用 StringFormat 将 XAML 中的时间戳(长类型)转换为日期和时间
我有一个 long
类型的时间戳属性,我已将其绑定到 ListView
列。 使用 XAML,我尝试将此时间戳(long
类型)转换为日期和时间,具体取决于正在运行的计算机的当前区域设置。
我想得到这样的信息:
mm/dd/yyyy HH:mm
或 dd/mm/yyyy HH:mm
(24 小时格式)
或
mm /dd/yyyy hh:mm
PM 或 dd/mm/yyyy hh:mm
PM(12 小时格式),
具体取决于计算机区域设置。
所以我使用 StringFormat
:
<GridViewColumn Header="Id"
DisplayMemberBinding="{Binding Path=Timestamp, StringFormat='g'}"/>
但它似乎不起作用。在网格视图单元格中,它显示为一个长数字。
I have a timestamp property which is a long
type and I have bound it to a ListView
column.
Using XAML I am trying to convert this timestamp (long
type) into a date and time dependent on the current regional settings of the machine on which is running.
I would like to get someting like this:
mm/dd/yyyy HH:mm
or dd/mm/yyyy HH:mm
(24 hour format)
or
mm/dd/yyyy hh:mm
PM or dd/mm/yyyy hh:mm
PM (12 hour format)
depending on the machine regional settings.
So I use StringFormat
:
<GridViewColumn Header="Id"
DisplayMemberBinding="{Binding Path=Timestamp, StringFormat='g'}"/>
But it seems it is not working. In the grid view cell it is shown as a long
number.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
g
是 通用格式说明符,它将把long
显示为数字。日期格式化机制不能直接与
long
一起使用。DateTime
对于表示日期和时间是明确的,但是如何将long
解释为秒、毫秒,从哪里解释?请参阅 的文档标准日期和时间格式字符串。显而易见的解决方案是通过
DateTime
类型的属性公开日期,而不是long
。然后,您可以在 XAMLStringFormat
中使用标准和自定义日期格式说明符。或者,您可以创建一个自定义值转换器,将
long
转换为DateTime
。在范围内的任何资源中创建转换器的实例,例如
Window.Resources
。自从转换发生在格式化之前,您可以保留
StringFormat
。您可以参考 自定义日期和时间格式字符串以创建所需的格式字符串。
更新您的评论:
我假设是 Unix 时间戳。正如您所看到的,
long
非常模糊。在这种情况下,您可以按照 文档。转换器方法将执行此操作。
The
g
is the general format specifier, which will display thelong
as number.The date formatting mechanism does not work directly with
long
. ADateTime
is unambiguous for representing a date and time, but how do you interpretlong
, as seconds, as milliseconds, from where? See the documentation for Standard date and time format strings.The obvious solution is to expose the dates through a property of type
DateTime
, notlong
. Then you can use the standard and custom date format specifiers in XAMLStringFormat
.Alternatively, you can create a custom value converter that converts the
long
to aDateTime
.Create an instance of the converter in any resources in scope, e.g.
Window.Resources
.Since the conversion happens before formatting, you can keep the
StringFormat
.You can refer to Custom date and time format strings to create the desired format string.
Update for your comment:
I assumed the Unix timestamp. As you can see, a
long
is pretty ambiguous. In this case you can convert thelong
back as stated in the documentation.The converter method would do exactly this.