Java Lesson 19: Fun with Dates and Times (in Java)

Advertisements

Hello everybody,

Michael here, and today I’ll be sharing a fun Java lesson on the use of dates and times in Java. I already covered date and time manipulation for both Python and R, but here’s the Java version of this concept.

Now, since the last time I posted a Java lesson, I got a new laptop, but I still plan to use NetBeans as my main IDE for these posts.

When working with dates and times in Java, keep in mind that unlike in Python, Java doesn’t have a single Date class/module that you can easily import or pip install. Java does have a java.time package which allows you to work with date/time manipulation. However, unlike with Python, you can’t import the whole package at once and expect to be able to use all of the package’s classes just like that. Rather, you’ll need to import all the package’s classes (the classes that you want to use) one by one-this is one of the major disadvantages of Java.

To start off our exploration of Java date-time manipulation, let’s first explore the Clock class of the java.time package. Some of the things that the Clock class can do is print out the current time (in both UTC and other time zones) and retrieve your current time zone-both of which would be useful when developing applications that deal with time zones. Execute this code and see what happens:

import java.time.Clock;
public class DateTime {

    public static void main(String[] args) 
    {
        Clock c = Clock.systemDefaultZone();
        System.out.println(c);
    }
    
}

SystemClock[America/Chicago]

Now, what exactly does this code do? Well, it creates an object of the Clock class and prints out the value of the object.

You’re likely wondering what systemDefaultZone is. It’s one of several methods in the Clock class. You can’t create an object of the Clock class on it’s own-by that I mean you can’t create a Clock object that looks like this: Clock c = Clock(). You’ll need to use of the class’s methods-in this case, I used the systemDefaultZone method. All this method does is print out the time zone your computer uses. Since I am in Nashville, TN right now, my system default [time] zone is [America/Chicago], as Chicago also uses Central Standard Time.

The Clock class has other methods, which you can find on this documentation from Oracle-https://docs.oracle.com/javase/8/docs/api/java/time/Clock.html. Explore this website for links related to some of the other classes that I will be discussing in this post.

Next up, let’s discuss the LocalDate class. This class allows you to display dates, but not datetimes or time zones. To start exploring the LocalDate class, let’s first create a simple LocalDate object:

import java.time.LocalDate;
public class DateTime {

    public static void main(String[] args) 
    {
        LocalDate ld = LocalDate.now();
        System.out.println(ld);
    }
    
}

2021-11-15

In this example, I created a simple LocalDate object that prints out today’s date using the .now() method (I ran this code on November 15, 2021). Just as with the Clock class, whenever you create a new object of the LocalDate class, you’ll need to include a class method with your object creation; in this case, I used the now() method of the LocalDate class.

Now, let’s explore some more methods of the LocalDate class by executing this code:

import java.time.LocalDate;
public class DateTime {

    public static void main(String[] args) 
    {
        LocalDate ld = LocalDate.now();
        System.out.println(ld.plusMonths(3));
        System.out.println(ld.getDayOfWeek());
        System.out.println(ld.isLeapYear());
        System.out.println(ld.toEpochDay());
    }
    
}

2022-02-15
MONDAY
false
18946

In this example, I still created a LocalDate object called ld that uses the LocalDate class’s .now() method. However, I added four output lines (referenced with System.out.println()) which generate four different outputs based on four different methods. Here’s an explanation of each output:

  • The first output-2022-02-15-was generated through the LocalDate class’s .plusMonths() method. The .plusMonths() method takes in one parameter-an integer that tells Java how many months to add to the date in the LocalDate object. In this case, I passed in 3 as the parameter of the .plusMonths() method, which tells Java to add 3 months to today’s date-the output is February 15, 2022.
  • The second output-MONDAY-was generated through the .getDayOfWeek() method, which in this case retrieves the current date’s day of the week. November 15, 2021 is a Monday, therefore this method will return MONDAY.
    • Recall that the current date in this example is November 15, 2021.
  • The third output-false-was generated through the .isLeapYear() method, which in this case returns either true or false depending on whether the current year is a leap year. Since 2021 isn’t a leap year, this method returned false.
  • The fourth output-18946-was generated through the interesting .toEpochDay() method. You wouldn’t need to use the .toEpochDay() method much, but I’ll discuss it here anyway. This method simply returns the number of days its been since January 1, 1970-the “epoch time” for computers. Why January 1, 1970? It’s basically an arbitrary date that serves as the “zero point” (or default time) for most operating systems.
    • On my old laptops, when the operating system was having issues, the system date would always be set to January 1, 1970.

Now that we’ve explored the LocalDate class a bit, let’s move on to the LocalTime class. LocalTime is basically the opposite of LocalDate since LocalTime only displays times and timestamps but no dates.

Let’s create a simple LocalTime object using the code below:

import java.time.LocalTime;
public class DateTime {

    public static void main(String[] args) 
    {
        LocalTime lt = LocalTime.now();
        System.out.println(lt);
    }
    
}

21:13:50.623089

Similar to the LocalDate example, I created a LocalTime object using the .now() method. And in case you hadn’t figured it out by now, you can’t create a LocalTime object without including a class method (just as you needed a class method for the Clock and LocalDate objects)

In this case, the LocalTime object I created printed out the current (at runtime) time as set on my laptop-21:13:50.623089. I ran the code at 9:13PM Central Standard Time, but Java will print out the time in 24-hour format (and 21 represents the 9PM hour).

Now, let’s explore four other methods of the LocalTime class (you’ll notice that this code looks syntactically similar to the code in the previous example):

import java.time.LocalDate;
import java.time.LocalTime;
import java.time.ZoneOffset;
public class DateTime {

    public static void main(String[] args) 
    {
        LocalTime lt = LocalTime.now();
        System.out.println(lt);
        System.out.println(lt.plusHours(6));
        System.out.println(lt.minusMinutes(45));
        System.out.println(lt.toNanoOfDay());
        System.out.println(lt.toEpochSecond(LocalDate.MAX, ZoneOffset.UTC));
    }
    
}

21:35:06.320094400
03:35:06.320094400
20:50:06.320094400
77706320094400
31556889832772106

Now, just as I did with the four methods in the LocalDate example, let’s explore the four methods I used here:

  • Below the lt output, you’ll see the output 03:35:06.320094400, which was generated from the .plusHours() method. This method takes in an integer parameter (6 in this case) and add that many hours to the current time-in this case, 6 hours from the current [run]time is 3:35AM.
  • The next output is 20:50:06.320094400, which was generated from the .minusMinutes() method. Like the .plusHours() method, the .minusMinutes() method takes in an integer (45 in this case) as the parameter. However, the .minusMinutes() method subtracts a certain amount of minutes from the LocalTime object-in this case, 45 minutes before the current [run]time is 10:50PM.
  • The next output is 77706320094400, which was generated from the .toNanoOfDay() method. This method returns the nanosecond of the current time. In this case, 9:35:06PM is roughly the 77.7 trillionth nanosecond of the day. If the current time was 12:00:00AM, the .toNanoOfDay() method would return 1, as this time would be the first nanosecond of the day.
    • Just so you know, 1 second is equal to a billion nanoseconds.
  • The last output is 31556889832772106, which was generated from the .toEpochSecond() method. This method is conceptually similar to the .toEpochDay() method, since both methods return the amount of time in a certain unit (days or second) since January 1, 1970. However, .toEpochSecond() returns the amount of seconds that have passed since January 1, 1970 at 12:00:00AM, which in this case is roughly 31.6 quadrillion seconds.
    • The ZoneOffset class was needed for the .toEpochDay() method, but don’t worry about it otherwise.

Next up, let’s explore the LocalDateTime class. You might be able to figure out what this class does based off the class name alone, but in case you didn’t, this class displays date-time objects-which are objects that display dates and times (in the same string).

As I did for both LocalDate and LocalTime, I will create a simple object of the LocalDateTime class using the .now() method:

import java.time.LocalDateTime;
public class DateTime {

    public static void main(String[] args) 
    {
        LocalDateTime ldt = LocalDateTime.now();
        System.out.println(ldt);
    }
    
}

2021-11-20T07:22:10.017889200

This example prints out the current date-time (at runtime)-November 20, 2021 at 7:22AM.

Now, let’s explore four different methods of the LocalDateTime class:

import java.time.LocalDateTime;
public class DateTime {

    public static void main(String[] args) 
    {
        LocalDateTime ldt = LocalDateTime.now();

        System.out.println(ldt.minusDays(60));
        System.out.println(ldt.plusMonths(4));
        System.out.println(ldt.withDayOfYear(60));
        System.out.println(ldt.getDayOfMonth());
    }
    
}

2021-09-21T07:29:56.515749900
2022-03-20T07:29:56.515749900
2021-03-01T07:29:56.515749900
20

Let’s explore each of the methods and their corresponding outputs:

  • The first output-2021-09-21T07:29:56.515749900-was generated through the LocalDateTime class’s .minusDays() method, which in this example takes in an integer as a parameter and subtracts that amount of days from the current date-time. In this case, 60 days subtracted from the current date-time equals September 21, 2021 at 7:29AM.
  • The second output-2022-03-20T07:29:56.515749900-was generated through the LocalDateTime class’s .plusMonths() method. Like the .minusDays() method, this method takes in an integer parameter; however, this method will add a certain number of months to the current date-time. In this case, 4 months added to the current date-time equals March 20, 2022 at 7:29AM.
  • The third output-2021-03-01T07:29:56.515749900-was generated through the .withDayOfYear() method. This is one of the LocalDateTime class’s more interesting methods since it oftentimes returns a different date from the date in the date-time object. This method, like the previous two I discussed, takes in an integer as a parameter; in this case, the method will return the date corresponding to the Xth day of the year. Since I passed 60 as the integer parameter, this method will return the date March 1, 2021 (the time part of the date-time object remains unchanged). Had I wrote and ran this code last year, this method would’ve returned February 29, 2020, as February 29 is the 60th day of the year in leap years.
  • The last output-20-was generated through the .getDayOfMonth() method. In this case, the method simply retrieves the day of the month of the current datetime; since the current date [as of runtime] is November 20, 2021, this method will return 20 since it’s currently the 20th day of the month.

Last but not least, let’s explore the DateTimeFormatter class. This class is different from the previous three classes we discussed because unlike those three classes, this class doesn’t return a datetime object. Rather, this class generates a formatted datetime object from an exisiting datetime object. Let me demonstrate this concept with the code below:

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
public class DateTime {

    public static void main(String[] args) 
    {
        LocalDateTime ldt = LocalDateTime.now();
        System.out.println("DateTime before formatting: " + ldt);
        DateTimeFormatter dtf = DateTimeFormatter.ofPattern("MM-dd-yy HH:mm");
        String formattedDateTime = ldt.format(dtf);
        System.out.println("DateTime after formatting: " + formattedDateTime);
    }
    
}

DateTime before formatting: 2021-11-28T09:01:48.974227300
DateTime after formatting: 11-28-21 09:01

Ok, so this example looks more complicated than our previous examples. As you can see from the code above, to be able to format a datetime object, we first need to create a datetime object of the LocalDateTime class.

Next, we’d need to create a datetime formatter object using the DateTimeFormatter class. We’d use this class’s .ofPattern() method and pass in a String pattern as the method’s parameter. In this example, I passed the pattern MM-dd-yy HH:mm into the .ofPattern() method; this pattern will display the datetime object with the date portion being displayed month first (followed by the day and year) and the time portion being displayed with just the hour and minute.

  • When specifying a datetime pattern to use for the .ofPattern() method, the month (MM) and hour (HH) will always be written with capital letters.
  • If you wanted to incorporate the full year into the output (2021 as opposed to just 21), you’ll need to write yyyy in place of yy.

Now, as you may have figured out from the code, the datetime formatter will only specify the pattern to use for the datetime object-the formatter (dtf) won’t actually format the DateTime object. Take a look at the line of code with the formattedDateTime object. In order to actually format the LocalDateTime object (ldt), you’ll need to use that object’s .format() method and pass in the object containing the pattern you want to use (dft in this case) as the .format() method’s parameter.

I also included two output lines-one that shows the current datetime before formatting and another one that shows the current datetime after formatting. Since I ran this code at 9:01AM Eastern Standard Time on November 28, 2021, the datetime object after formatting is 11-28-21 09:01.

Thanks for reading,

Michael

Colors in Programming

Advertisements

Hello everybody,

Michael here, and today’s lesson will be a little different from my usual content. See, I won’t cover any coding technique per se, but as you may have guessed from the title, I’ll be discussing colors in programming. And no, this won’t be a preschooler’s lesson on color, nor will this be an art-class lesson on color-this is directed towards programmers (who will likely need to know how to use colors in their applications no matter what tool you use for development).

First of all, before we start discussing colors in programming, let’s get into a little history lesson. In 1666, Sir Issac Newton developed his theory that all colors are made up of mixtures of red, green, and blue light. Here’s a picture of that color wheel:

https://www.google.com/url?sa=i&url=https%3A%2F%2Fwww.the-scientist.com%2Ffoundations%2Fnewtons-color-theory-ca-1665-31931&psig=AOvVaw0Rhnfp6Abx_fTYLkHxywJB&ust=1636428109116000&source=images&cd=vfe&ved=0CAsQjRxqFwoTCJikrPjnh_QCFQAAAAAdAAAAABAD

And here’s a more modern interpretation of the color wheel:

https://www.google.com/url?sa=i&url=https%3A%2F%2Fuxplanet.org%2Fanalogous-colors-and-color-wheel-609a05b5b90e&psig=AOvVaw28hxAuUrzxPNZcVud3tC1T&ust=1636428142353000&source=images&cd=vfe&ved=0CAsQjRxqFwoTCOD6kIPoh_QCFQAAAAAdAAAAABAG

In programming (and in general), the three primary colors are red, green, and blue (which you can see from the color wheel above). Secondary colors, such as orange and purple, are created by mixing two primary colors together. Tertiary colors, such as light orange and dark green, are created by mixing a primary and a secondary color together.

Now that we’ve covered some very basic color theory concepts, let’s start discussing how to use colors in programming.

To really understand how colors are used in programming, we’ll cover four basic programming color schemes-RGB, HEX, HSL, and CMYK. Don’t worry-I’ll explain each of these color schemes in detail.

First, let’s discuss the RGB color scheme. As to what RGB stands for, it may be obvious to some of you, but for those who don’t know, RGB stands for red, green, blue. Remember how I said that Newton theorized that all colors are created from some mixture of red, green, and blue light? This color scheme exemplifies that theory, as it allows you to create colors based off a combination of red, green, and blue.

How would that work exactly? Well, RGB color values are usually specified as RGB(red, green, blue). The red, green, and blue parameters in the RGB() function defines the intensity of the red, green, or blue you want to use in a particular color; the intensity is represented as an integer between 0 and 255.

For instance, pure red would be represented by the RGB code RGB(255, 0, 0):

So how did RGB(255, 0, 0) generate a pure red? Well, since the red value is 255 and the green and blue values are 0, this indicates a pure red color will be generated, as the red value is as high as it can be-255.

Similarly, RGB(0, 255, 0) will generate a pure green and RGB(0, 0, 255) will generate a pure blue.

Now, how would you generate pure black and pure white? Here’s what pure black would look like:

To generate pure black, use the RGB code RGB(0, 0, 0). To generate pure white, use the RGB code RGB(255, 255, 255).

Now, what if you wanted to generate a color that wasn’t red, blue, green, black or white? Let’s say you wanted to create orange with the RGB color scheme. Here’s what pure orange would look like:

To create pure orange, I used the RGB code RGB(255, 165, 0).

Next, let’s discuss the HEX color scheme. In the HEX color scheme, colors are represented with hexadecimal numbers, which include the numbers 0-9 and the letters A-F (for a refresher on the hexadecimal numbering system, refer to this entry-Java Lesson 5: Java Numbering Systems-an oldie but a goodie).

The HEX color scheme is similar to the RGB color scheme since both color schemes generate colors from some combination of red, blue, and green. HEX colors are represented as #RRGGBB, with red (RR), green (GG) and blue (BB). Also, just like RGB colors, the intensities of the red, green, and blue colors are represented by a range of integers, but unlike the color intensities of RGB colors, HEX color intensities are represented by hexadecimal integers ranging from 00 (least intense) to FF (most intense). For instance, let’s say you wanted to generate pure red via the HEX color scheme. Here’s the hex code you would use-#FF0000. The hex code #FF0000 generates the same color as the RGB code RGB(255, 0, 0)-that’s because in both cases, the red in each color code is at its most intense value (255 for the RGB code, FF for the HEX code). Similar to the pure red example I just discussed, to generate pure green, use the HEX code #00FF00 and to generate pure blue, use the HEX code #0000FF.

  • If you want to create a HEX color, then always remember to place the pound sign/hashtag/whatever you want to call it (#) in front of the color HEX code. If you don’t do this, the program you’re working with (whether Python, HTML, etc.) won’t know you’re trying to create a color.

Don’t believe me? Well, let’s take a look at the pure red, pure green, and pure blue generated from HEX:

Pure red:

Pure green:

Pure blue:

Now, what if you wanted to generate pure black and pure white using the HEX color scheme? For pure black, use the hex code #000000 and for pure white, use the hex code #FFFFFF.

Next, let’s discuss the HSL color scheme. This color scheme is different from the previous two because in the HSL color scheme, colors aren’t generated from a combination of red, green, and blue. HSL stands for hue, saturation, and lightness. Hue refers to a degree on the color wheel that is represented by an integer between 0 and 360-0 refers to red, 120 to blue, and 240 to green. Saturation refers to the percentage of grey in a certain color; it is represented as a percentage value from 0-100%. 0% means there is a shade of grey in a certain color while 100% means there is no grey in the color. Lightness refers to percentage of, well, light in a certain color. 0% means a pure black color while 100% means a pure white color.

So, what would pure red, pure green, and pure blue look like with the HSL color scheme. Let’s take a look:

Here’s how pure red looks with the HSL color scheme:

To generate pure red with the HSL color scheme, use the code HSL(0, 100%, 50%)-and yes, you’ll need to remember to include the percent signs.

Now, if you wanted to generate pure green with the HSL color scheme, use the code HSL(120, 100%, 50%). Likewise, if you wanted to generate pure blue with the HSL color scheme, use the code `HSL(200, 100%, 50%).

Now, what if you wanted to generate pure black and pure white with the HSL color scheme? To generate pure white, use the code HSL(0, 100%, 100%). To generate pure black, use the code HSL(0, 0%, 0%).

Last but not least, I’ll discuss the CMYK color scheme. The CMYK color scheme is similar to the RGB color scheme since both color schemes generate colors from combinations of other colors. However, unlike with RGB colors, CMYK colors are generated from a combination of cyan, magenta, yellow, and key black. Also, RGB colors are mainly used by computer screens to display content onscreen while CMYK colors are mainly used by printers to present printed content.

  • In case you guys didn’t know, cyan is a shade of blue, magenta is a shade of pink, and key black refers to the type of black color used in printer ink cartridges.

CMYK colors are represented as percentages (from 0% to 100%) of cyan, magenta, yellow, and key black. To generate a CMYK color, use this code-CMYK(100%, 0%, 0%, 0%); this code generates pure cyan.

  • When generating CMYK colors, always remember to include the percent signs!!

Now, what if you wanted to generate pure red? It’s a little different with the CMYK color scheme because, unlike with the RGB and HEX color schemes, colors aren’t being generated as a combination of red, green, and blue. Now, to generate pure red with the CMYK color scheme, use the code CMYK(0%, 100%, 100%, 0%). This code tells your program to use 0% cyan, 100% magenta, 100% yellow, and 100% key black to create the pure red.

To create pure green using the CMYK color scheme, use the code CMYK(100%, 0%, 100%, 0%). To create pure blue using the CMYK color scheme, use the code CMYK(100%, 100%, 0%, 0%).

Now, what if you wanted to create pure black and pure white with the CMYK color scheme? To create pure black, use the code CMYK(0%, 0%, 0%, 100%). This makes sense, as you’d need 100% key black to create pure black. Now, to create pure white, use the code CMYK(0%, 0%, 0%, 0%).

Now that I’ve discussed each of the color schemes, let’s discuss another important color-related tool in programming-color palettes. Color palettes are simply collections of colors used in a single medium-such as a website, a piece of art, a three piece suit collection, etc. For the purposes of this blog, we’ll focus on color palettes in a programming context. Color palettes are widely used in programming to set the design of a particular application (like the design company webpage). Many large companies, such as Google, Netflix, and Amazon, among others, use color palettes for their logos and websites.

Even sports teams use their own color palettes. The Cleveland Browns NFL team uses a 3-color color palette-brown, orange, and white (as you can see on their uniforms below):

https://www.google.com/url?sa=i&url=https%3A%2F%2Fen.wikipedia.org%2Fwiki%2FCleveland_Browns&psig=AOvVaw0KI_qwSJ9W9gL7t3jAMWw9&ust=1636428160939000&source=images&cd=vfe&ved=0CAsQjRxqFwoTCPi92ozoh_QCFQAAAAAdAAAAABAD
  • Sometimes I may use the term color schemes instead of color palettes, but these terms mean the same thing and can be used interchangeably.

Several programming tools have their own color palettes that are exclusive to that particular tool. For instance, Python’s MATPLOTLIB library has its own collection of color schemes-check out this link to find out more about MATPLOTLIB’s color schemes (referred to as colormaps on the site) https://matplotlib.org/stable/tutorials/colors/colormaps.html.

Now, last but not least, I want to share a neat color scheme finder/generator tool with you-it’s called coolors.co.

The reason I refer to this tool as a color scheme finder/generator is because this tool will not only allow you to find the perfect color scheme for whatever tool you’re building but also allow you to generate custom color schemes.

First, let’s click on the Explore button to explore some color schemes:

As you can see, you can scroll down the page to discover several different color schemes. Now, the great thing about each of these color schemes is that you don’t need to import them to whatever program you’re using; rather, all you need to do is simply hover over each color in a particular color scheme to get that color’s HEX code. Once you have all the HEX codes for all the colors in a certain color scheme, you can start incorporating the colors into your program.

However, what would you do if you wanted to find color palettes based off a single color (let’s use yellow for this example)? You would type in the name of a color in the Search bar and click Enter:

As you can see, searching for yellow returned several yellow color palettes. However, whenever you search for a color in the search bar, you won’t get only monochromatic color palettes. In case you didn’t know, monochromatic color palettes use different shades of a single color-in this case, monochromatic color palettes would use different shades of yellow. As you can see above, searching for yellow color palettes also returns color palettes with other colors, such as greens and blues.

Now, what if you wanted to generate a color palette for future use? Click on the Generate link to start generating color schemes:

As you can see, a randomly generated 5-color color palette appears, complete with the color names and hex codes ready for you to use on whatever application you are currently developing.

Now, press the spacebar (but don’t leave the Generate page) and watch what happens:

As you can see, when you press the spacebar, a new random 5-color color palette is generated, complete with color names and hex codes.

  • Since the 5-color color palettes are generated at random, your results will certainly differ from mine.

Thanks for reading,

Michael