Erlang 中带前导零的格式
我想以字符串形式返回当地时间,但带有前导零。我尝试了这个:
{{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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
尝试:
io_lib:format/2
(及其同伴io:format/2
)实际上返回一个深度IO列表。这样的列表是可打印的,并且可以在套接字上发送或作为平面字符串写入文件,但生成效率更高。扁平化通常是无用的,因为在字符串被打印或输出到文件/套接字的所有情况下,Erlang 都会自动将其扁平化。Try:
io_lib:format/2
(and it's companionio: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.您希望使用这样的内容:
更常见的
w
格式修饰符在这里可以做正确的事情,与 base 等一起使用,因此无需使用更复杂的B
修改器。2..0
表示“2 个字符宽,零填充,未指定精度”。我们在这里不需要精度,因为我们正在处理整数。You want to be using something like this:
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 complexB
modifier.2..0
says "2 characters wide, zero padded, no precision specified." We don't need precision here, since we're dealing with integers.