Wednesday, July 18, 2012

Working with Dates/Numbers and Currencies


In this section you'll learn the most common methods to format Dates, Numbers and Currencies as well as the relationship between the main classes responsible to do that.

Let's start with the classes that you have to learn.

java.util.Date;
java.util.Calendar;
java.text.DateFormat;
java.text.NumberFormat;
java.util.Locale;


Console:

Wed Jul 18 10:18:42 AMT 2012
Wed Dec 31 19:16:40 AMT 1969
1342621122734
Wed Jul 18 10:18:42 AMT 2012
Sun Nov 21 04:58:20 AMT 2286

The class java.util.Date is hard to work with,if you look at the preceding example to set a specific date we have to use a number representation(long), this class is normally used to create a date that represents "now" as well as working with java.util.Calendar.


Console:

Sat Sep 15 00:00:00 AMT 2012
Today is Wed Jul 18 10:37:26 AMT 2012
Day of the week 4
Day of the year 200
Last day of the year 259
Remaining Days ==> 59
Fri Jul 18 10:37:26 AMT 2014
Sun May 18 10:37:26 AMT 2014


Watch out, the class Calendar is abstract you cannot create an instance of it(look at line 16), also it provides friendly methods to manipulate dates, where you can add hours, days, weeks, and so on.
Notice the class java.util.Calendar work together java.util.Date, instead of setting a date using number(long) you can use a Date object.
Finally the method roll is similar to add, the difference is it does not change into next month(if you're adding days), years(if you're adding months) and so on.


Console:

Friday, August 17, 2012
Sexta-feira, 17 de Agosto de 2012
vendredi 17 août 2012
viernes 17 de agosto de 2012
2012?8?17?
Parse ==> Fri Aug 17 00:00:00 AMT 2012


The class java.text.DateFormat is an abstract class that provides us formatted dates using or not pré-defined styles as well as Locales.
You can get a DateFormat class by invoking the methods getInstance() and getDateInstance().
Finally we can parse a String to Date by using the method parse() which must be enclosed in a try-catch block.


Console:

pt ->
pt -> Brasil
fr ->
en -> United States


Let's take a briefly look at java.util.Locale.

The first argument is related to the language and the second is a country.
The most important methods are getLanguage() and getDisplayCountry().
There are not setters to define language and country at java.util.Locale.


Console:

1.100,56848
1.100,568
1,100.568
R$ 1.100,57
¤ 1.100,57
$1,100.57
5
1234567
1234567


Similar to java.text.DateFormat the class java.text.NumberFormat works with numbers(currency, percent, and so on), where there are many ways to get a concrete class since NumberFormat is abstract.

getInstance(),
getNumberInstance(),
getCurrencyInstance(),
.. and so on

The method parse() is present as well where you can get a Number object.

No comments: