Showing posts with label Java 8. Show all posts
Showing posts with label Java 8. Show all posts

Monday, May 12, 2014

Lambda Expressions: Java 8

A couple of months back, I heard that Java 8 was out and while reading about it online, I kept coming across Lambda Expressions as a pretty important feature included. At that time, I did not have the time to look in detail of what it is and how it works. I was able to get the concept and idea of why Date & Time API was revamped completed. However, I was curious about what Lambda Expressions are and how and if I would ever use them in real life.
That was until I ran across the below article that paints a pretty neat picture of the use cases and syntax:
Lambda Expressions in Java 8

Please try it out...

Wednesday, May 7, 2014

Using Calendar to find the # of days between 2 Date's

I am pretty sure most of you have done something like this before and it is a very simple solution. The below piece of code is to find the Period between two java.util.Date fields using the Calendar object:

import java.util.Date;
import java.util.Calendar;

public class CalendarTest{

     public static void main(String []args){
        Date fromDate = new Date();
        Date toDate = new Date();
       
        Calendar fromCal = Calendar.getInstance();
        Calendar toCal = Calendar.getInstance();
       
        fromCal.setTime(fromDate);
        toCal.setTime(toDate);
       
        int range = toCal.get(Calendar.DAY_OF_YEAR) - fromCal.get(Calendar.DAY_OF_YEAR);
       
        System.out.println("Range: " + range);
     }
}

The above is how you would have to do in and upto Java 7. However, Java 8 has a brand new Date and Time API and I am going to give it try and see how it looks.

public class Java8TimeTest
{
  public static void main(String[] args)
  {
    LocalDate today = LocalDate.now();
    LocalDate dayInFuture = LocalDate.of(2020, Month.JANUARY, 1);
   
    long dayCount = ChronoUnit.DAYS.between(today, dayInFuture);
    System.out.println("There are " + dayCount + " days left until 2020");
  }
}

Trying out for the first time, the API's are very intuitive and I am loving it. Let upgrade to Java 8 soon!!!