2

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.

2 Answers 2

6

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.

3
  • Thanks. Flattening the list returns the correct string. I use the current time to build a filename. I only wonder where this ["0",57] comes from? Thanks again. Commented Sep 29, 2011 at 15:27
  • 1
    57 is the ASCII code for "9". Flattening is just forcing the formatted return value to a single string, so the whole thing gets interpreted as ASCII. Remember, in Erlang, normal strings are just arrays of integers. The erl environment has to guess how you want a given array of integers to be interpreted. It happens to have guessed wrong in your case, but really, it's doing the same thing. Commented Sep 29, 2011 at 15:39
  • 1
    A clarification to Adam's great answer is that io:format("~s", [DateAsString]) prints exactly what you are asking for. (Also try io:format("~s", [["0", 57]]) to see that "09" and ["0", 57] are the same from an io point of view.) Commented Sep 29, 2011 at 17:56
3

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.

1
  • Thanks for the reply. The ~2..0w actually returns the same result. Commented Sep 29, 2011 at 15:25

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.