© Adam L. Davis 2020
A. L. DavisModern Programming Made Easyhttps://doi.org/10.1007/978-1-4842-5569-8_12

12. Utilities

Adam L. Davis1 
(1)
Oviedo, FL, USA
 

There are many classes, functions, or objects (sometimes called utilities) that come built-in with each programming language that can be very useful. The java.util package contains many useful classes for everyday programming. Likewise, JavaScript and other languages come with many built-in objects for doing common tasks. I am going to cover a few of these.

Dates and Times

You should never store date values as text. It’s too easy to mess up (Figure 12-1).
../images/435475_2_En_12_Chapter/435475_2_En_12_Fig1_HTML.jpg
Figure 12-1

I can has string to store date valyooz?

Java Date-Time

Java 8 introduced a new and improved date-time application program interface (API) in the java.time package that is much safer, easier to read, and more comprehensive than the previous API.

For example, creating a date looks like the following:
1   LocalDate date = LocalDate.of(2014, Month.MARCH, 2);

There’s also a LocalDateTime class to represent date and time, LocalTime to represent only time, and ZonedDateTime to represent a time with a time zone.

Before Java 8, there were only two built-in classes to help with dates: Date and Calendar. These should be avoided when possible.
  • Date actually represents both a date and time.

  • Calendar is used to manipulate dates.

In Java 7 and lower, you would have to do the following to add five days to a date:
1   Calendar cal = Calendar.getInstance();
2   cal.setTime(date);
3   cal.add(5, Calendar.DAY);
Whereas in later versions of Java, you could do the following:
1   LocalDate.now().plusDays(5)

Groovy Date

Groovy has a bunch of built-in features that make dates easier to work with. For example, numbers can be used to add/subtract days, as follows:
1   def date = new Date() + 5; //adds 5 days
Groovy also has TimeCategory1 for manipulating dates and times. This lets you add and subtract any arbitrary length of time. For example:
1   import groovy.time.TimeCategory
2   now = new Date()
3   println now
4   use(TimeCategory) {
5       nextWeekPlusTenHours = now + 1.week + 10.hours - 30.seconds
6   }
7   println nextWeekPlusTenHours

A Category is a class that can be used to add functionality to other existing classes. In this case, TimeCategory adds a bunch of methods to the Integer class.

Categories

This is one of the many meta-programming techniques available in Groovy. To make a category, you create a bunch of static methods that operate on one parameter of a particular type (e.g., Integer). When the category is used, that type appears to have those methods. The object on which the method is called is used as the parameter. Take a look at the documentation for TimeCategory for an example of this in action.

JavaScript Date

JavaScript also has a built-in Date2 object.

You can create an instance of a Date object in several ways (these all create the same date):
1   Date.parse('June 13, 2014')
2   new Date('2014-06-13')
3   new Date(2014, 5, 13)

Note that if you adhere to the international standard (yyyy-MM-dd), a UTC time zone will be assumed; otherwise, it will assume you want a local time.

As usual with JavaScript, the browsers all have slightly different rules, so you have to be careful with this.

../images/435475_2_En_12_Chapter/435475_2_En_12_Figa_HTML.jpg Don’t ever use getYear! In both Java and JavaScript, the Date object’s getYear method doesn’t do what you think and should be avoided. For historical reasons, getYear does not actually return the year (e.g., 2014). You should use getFullYear() in JavaScript and LocalDate or LocalDateTime in Java.

Java DateFormat

Although DateFormat is in java.text, it goes hand in hand with java.util.Date.

The SimpleDateFormat is useful for formatting dates in any format you want. For example:
1   SimpleDateFormat sdf = new  SimpleDateFormat("MM/dd/yyyy");
2   Date date = new  Date();
3   System.out.println(sdf.format(date));

This would format a date per the US standard: month/day/year.

Java 8 introduced the java.time.format.DateTimeFormatter to format or parse using the new date and time classes. Each java.time class, such as LocalDate, has a format method and a static parse method which both take an instance of DateTimeFormatter.

For example:
1  LocalDate date = LocalDate.now();
2  DateTimeFormatter formatter = DateTimeFormatter.ofPattern("MM/dd/yyyy");
3  String text = date.format(formatter);
4  LocalDate parsedDate = LocalDate.parse(text, formatter);

../images/435475_2_En_12_Chapter/435475_2_En_12_Figb_HTML.jpg More Formatting See the documentation for SimpleDateFormat3 for more information about it. See the DateTimeFormatter4 documentation for more about it.

Currency

In Java, java.util.Currency is useful if your code has to deal with currencies in several countries. It provides the following methods:
  • getInstance(Locale): Static method to get an instance of Currency based on Locale

  • getInstance(String): Static method to get an instance of Currency based on a currency code

  • getSymbol(): Currency symbol for the current locale

  • getSymbol(Locale): Currency symbol for the given locale

  • static getAvailableCurrencies(): Returns the set of available currencies

For example:
1   String pound = Currency.getInstance(Locale.UK).getSymbol(); // GBP
2   String dollar = Currency.getInstance("USD").getSymbol(); // $

TimeZone

In Java 8 and above, time zones are represented by the java.time.ZoneId class . There are two types of ZoneIds, fixed offsets and geographical regions. This is to compensate for practices such as daylight saving time, which can be very complex.

You can get an instance of a ZoneId in many ways, including the following two:
1   ZoneId mountainTime = ZoneId.of("America/Denver");
2   ZoneId myZone = ZoneId.systemDefault();
To print out all available IDs, use getAvailableZoneIds(), as follows:
1   System.out.println(ZoneId.getAvailableZoneIds());

../images/435475_2_En_12_Chapter/435475_2_En_12_Figc_HTML.jpg Write a program that does this and run it. For example, in the groovyConsole, write the following and execute:

import java.time.*

println(ZoneId.getAvailableZoneIds())

Scanner

Scanner can be used to parse files or user input. It breaks the input into tokens, using a given pattern, which is whitespace by default (“whitespace” refers to spaces, tabs, or anything that is not visible in text).

For example, use the following to read two numbers from the user:
1   System.out.println("Please type two numbers");
2   Scanner sc = new Scanner(System.in);
3   int num1 = sc.nextInt();
4   int num2 = sc.nextInt();

../images/435475_2_En_12_Chapter/435475_2_En_12_Figd_HTML.jpg Write a program that does this and try it out. Since this requires input, it can’t be done with the groovyConsole. Use either NetBeans to build a Java application or a Groovy script you run with groovy on the command line.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset