Format with leading zeros in Erlang - erlang

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.

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.

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.

Related

How to set the number of digits while printing in Java?

I couldn't really clarify what I'm asking in the title. I an integer for a day and a month. I have to print the month with a 0 in front of it if it's one digit only.
For example 04 if month = 4 and so on.
This is how it's supposed to look like in C#:
Console.WriteLine("{0}.{1:00}", day, month);
Thank you.
int month = 4;
DecimalFormat formater = new DecimalFormat("00");
String month_formated = formater.format(month);
Besides the answer Fernando Lahoz provided (which is pretty specific to your case: decimal formating) you can also use System.out.format in Java which allows you to specify a format-string while printing to System.out (the format function is applicable to any PrintStream though). In your case
System.out.format("%2d %2d", day, month)
should do the trick. The %dis used for decimal integers and you can then specify any width you want just before the 'd' (2 in your case).
If you want to access the string formed for later use and not (only) print it you can use String.format. It uses the same format as System.out.format but returns the String that is formed.
A complete syntax for all formats(string, decimal, floating point, calendar, date/time, ...) can be found here.
If you'd like a quick tuto on number-formatting you can check this link or this link instead.
Good luck!

How to parse a time value of type UTCTime from string in Haskell?

This is a follow-up question to the one I asked just a little while ago.
I couldn't find a single example (sorry for my Google skills) on the Haskell site which shows how to use the Data.Time functions to convert a formatted String to UTCTime and then be able to add/subtract minutes/seconds from that and convert back the UTCTime to formatted String.
I am looking for an example that shows how to convert a String (e.g. like "10:20:30" to UTCTime and then add 1000 seconds to that time. How to do this Haskell using the Data.Time library without using IO at all?
The type of the function should be FormatTime -> String -> UTCTime.
The function should use TimeLocale or FormatTime as locale/formatting is needed.
There are so many functions in the library and so many types that it just baffling. readTime, TimeLocale, ParseTime t, NominalDiffTime, Time and what not.
Please do not just point to docs on the Haskell site. Most of the docs there are just a dump of type signatures from the source code, without almost any examples. Sorry if this is coming as rant, but I have spent a lot of time trying to figure out something from those docs.
Compare this to Python docs on time. So many beautiful examples.
Thank god, there is SO.
import Data.Time
timeFormat = "%H:%M:%S"
understandTime = parseTimeOrError True defaultTimeLocale timeFormat
time :: UTCTime
time = understandTime "10:30:20"
λ> time
1970-01-01 10:30:20 UTC
Let's break down what's going on:
timeFormat is simply a string, describing how we expect the time to be passed to us.
we partially apply parseTimeOrError, using defaultTimeLocale for the locale, and previously defined timeFormat for the expected format.
We now have a understandTime function, that can take in a time as a String. When using it, we need to explicitly set the expected output type to UTCTime (this is what time :: UTCTime does). If we were to use understandTime within the context of a function that already expects a UTCTime, this would be unnecessary (for example addUTCTime 1000 (understandTime "10:30:20"))
We get back time. Note that the year, day, month and timezone default to 1970-01-01 and UTC because we do not explicitly read them in timeFormat.

what's this date format ? 2006-09-01T07:00:00.000+0000 ? is it ISO_8601 ?

I am working on REST calls where I need to send date in "2006-09-01T07:00:00.000+0000" format.
User enters date in "YYYY/MM/DD" format and I am using "moment.js" to format the date in ISO 8601 using this format "YYYY-MM-DDTHH:MM:SS.MMMZ" . But it gives me this output "1969-06-20T00:06:00.Jun-07:00".
So, how do I get date in this format "2006-09-01T07:00:00.000+0000" using moment.js OR Javascript ?
Yes, it is ISO 8601. 2006-09-01T07:00:00.000+0000 is the first day of the ninth month of the year 2006, 7 hours, 0 minutes, 0.000 seconds offset 0 hours from UTC. Whether or not decimals are allowed is up to the parties exchanging dates (which is a fancy way of ISO saying "it's optional").
4.2.2.4 Representations with decimal fraction
If necessary for a particular application a decimal fraction of hour, minute or second may be included. If a decimal fraction is included, lower order time elements (if any) shall be omitted and the decimal fraction shall be divided from the integer part by the decimal sign specified in ISO 31-0, i.e. the comma [,] or full stop [.]. Of these, the comma is the preferred sign. If the magnitude of the number is less than unity, the decimal sign shall be preceded by two zeros in accordance with 3.6.
The interchange parties, dependent upon the application, shall agree the number of digits in the decimal fraction. The format shall be [hhmmss,ss], [hhmm,mm] or [hh,hh] as appropriate (hour minute second, hour minute, and hour, respectively), with as many digits as necessary following the decimal sign. A decimal fraction shall have at least one digit. In the examples below it has been agreed to give the smallest time element a decimal fraction with one digit.
(As pointed out by #chansen, technically it should be 2006-09-01T07:00:00.000+00:00 with a separator on the time zone because according to 4.3.3(d) every part must use either the basic format (no separators) or the extended format (with separators), but nobody bothers with that, strptime can't produce that format, and you'll probably break some ISO 8601 parsers).
Outputting this is covered in other answers for both Javascript and moment.js.
Javascript has Date.toISOString for output. Date.new will also accept an ISO 8601 string. Every recent browser should support it, though Internet Explorer only added it in version 9 (IE 8 still represents 5% of desktop users).
Here's the moment.js docs on String formatting. YYYY-MM-DDTHH:MM:SS.MMMZ is incorrect because you're using M to mean three different things. What you want is YYYY-MM-DDTHH:mm:ss.SSSZZ.
YYYY - year
MM - month number (2 digit)
DD - day of month (2 digit)
HH - hours (2 digit, 24 hour format)
mm - minutes (2 digit)
ss - seconds (2 digit)
SSS - thousands of seconds
ZZ - UTC offset
The format that worked for me for 2006-09-01T07:00:00.000+0000
was: yyyy-MM-dd'T'hh:mm:ss.sssZ

Parsing date and time with the new java.time.DateTimeFormatter

I have a date of this type: 2004-12-31 23:00:00-08 but no one of the patterns i know and i have used from the documentation is working. I thought it should something like "yyyy-MM-dd HH:mm:ssX" but it isn't working.
Sorry for you, but this is a known bug and was already reported in January 2014. According to the bug log a possible solution is deferred.
A simple workaround avoiding alternative external libraries is text preprocessing. That means: Before you parse the text you just append the prefix ":00". Example:
String input = "2004-12-31 23:00:00-08";
String zero = ":00";
if (input.charAt(input.length() - 3) == ':') {
zero = "";
}
ZonedDateTime zdt =
ZonedDateTime.parse(
input + zero,
DateTimeFormatter.ofPattern("uuuu-MM-dd HH:mm:ssXXX"));
System.out.println(zdt);
// output: 2004-12-31T23:00-08:00
UPDATE due to debate with #Seelenvirtuose:
As long as you ONLY have offsets with just hours but without minute part then the pattern "uuuu-MM-dd HH:mm:ssX" will solve your problem, too (as #Seelenvirtuose has correctly stated in his comment).
But if you have to process a list of various strings with mixed offsets like "-08", "Z" or "+05:30" (latter is India standard time) then you should usually apply the pattern containing three XXX. But this currently fails (have verified it by testing in last version of Java-8). So in this case you still have to do text preprocessing and/or text analysis.

How to convert Float to String with out getting E in blackberry

Any way to convert Float to string with out getting E (exponent).
String str = String.valueOf(floatvalue);
txtbox.settext(str);
and i am using NumericTextFilter.ALLOW_DECIMAL in my textField which allow decimal but not E.
i am getting like this 1.3453E7 but i want it something like 1.34538945213 due to e i am not able to set my value in edit text.
so any way to get value with out e.
I'm not 100% sure I understand what number you're trying to format. In the US (my locale), the number 1.3453E7 is not equal to the number 1.34538945213. I thought that even in locales that used the period, or full stop (.) to group large numbers, you wouldn't have 1.34538945213. So, I'm guessing what you want here.
If you just want to show float numbers without the E, then you can use the Formatter class. It does not, however, have all the same methods on BlackBerry that you might expect on other platforms.
You can try this:
float floatValue = 1.3453E7f;
Formatter f = new Formatter();
String str = f.formatNumber(floatValue, 1);
text.setText(str);
Which will show
13453000.0
The 1 method parameter above indicates the number of decimal places to show, and can be anything from 1 to 15. It can't be zero, but if you wanted to display a number without any decimal places, I would assume you would be using an int or a long for that.
If I have misunderstood your problem, please post a little more description as to what you need.
I'll also mention this utility class that apparently can be used to do more numeric formatting on BlackBerry, although I haven't tried it myself.
Try this:
Double floatValue = 1.34538945213;
Formatter f = new Formatter();
String result = f.format("%.11f", floatValue);
Due to the floating point presentation in java, the float value 1.34538945213 has not the same representation as the double value 1.34538945213. So, if you want to get 1.34538945213 as output, you should use a double value and format it as shown in the example.

Resources