Erlang 中带前导零的格式

发布于 2024-12-07 05:41:21 字数 440 浏览 0 评论 0原文

我想以字符串形式返回当地时间,但带有前导零。我尝试了这个:

{{Year, Month, Day}, {Hour, Minute, Second}} = erlang:localtime().
DateAsString = io_lib:format("~2.10.0B~2.10.0B~4.10.0B~2.10.0B~2.10.0B~2.10.0B", 
           [Month, Day, Year, Hour, Minute, Second]).

但如果某些组件是一位数字,则返回的字符串为:

[["0",57],"29","2011","17","33","34"]

当前月份 9 打印为 ["0",57]

请帮忙。

谢谢。

I would like to return the local time as string but with leading zeros. I tried this:

{{Year, Month, Day}, {Hour, Minute, Second}} = erlang:localtime().
DateAsString = io_lib:format("~2.10.0B~2.10.0B~4.10.0B~2.10.0B~2.10.0B~2.10.0B", 
           [Month, Day, Year, Hour, Minute, Second]).

But if some of the components is one digit, the returned string is:

[["0",57],"29","2011","17","33","34"]

The current month 9 is printed as ["0",57].

Please, help.

Thank you.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

吐个泡泡 2024-12-14 05:41:21

尝试:

1> lists:flatten([["0",57],"29","2011","17","33","34"]).
"09292011173334"

io_lib:format/2(及其同伴io:format/2)实际上返回一个深度IO列表。这样的列表是可打印的,并且可以在套接字上发送或作为平面字符串写入文件,但生成效率更高。扁平化通常是无用的,因为在字符串被打印或输出到文件/套接字的所有情况下,Erlang 都会自动将其扁平化。

Try:

1> lists:flatten([["0",57],"29","2011","17","33","34"]).
"09292011173334"

io_lib:format/2 (and it's companion io:format/2) actually returns a deep IO list. Such a list is printable and can be sent on a socket or written to a file just as a flat string, but is more efficient to produce. Flattening is often useless, because in all cases where the string will be printed or output to a file/socket it will automatically be flattened by Erlang.

山有枢 2024-12-14 05:41:21

您希望使用这样的内容:

DateAsString = io_lib:format("~2..0w~2..0w~4..0w~2..0w~2..0w~2..0w", 
       [Month, Day, Year, Hour, Minute, Second]).

更常见的 w 格式修饰符在这里可以做正确的事情,与 base 等一起使用,因此无需使用更复杂的 B 修改器。 2..0 表示“2 个字符宽,零填充,未指定精度”。我们在这里不需要精度,因为我们正在处理整数。

You want to be using something like this:

DateAsString = io_lib:format("~2..0w~2..0w~4..0w~2..0w~2..0w~2..0w", 
       [Month, Day, Year, Hour, Minute, Second]).

The more common w format modifier does the right thing here, what with base and such, so there's no need to use the more complex B modifier. 2..0 says "2 characters wide, zero padded, no precision specified." We don't need precision here, since we're dealing with integers.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文