What is Directive in AngularJS?

Posted on Updated on

What is Directive in AngularJS?

Directives are core building blocks of AngularJS which are used to create custom HTML tags and can be placed in element names, attributes and comments. Directives can be used as HTML directives which build complex widgets with layered functionality.

Scope in Directive in AngularJS?

Unlike the other MVC frameworks, AngularJS doesn’t have specific classes or functions to create model objects. Instead, AngularJS extended the raw JavaScript objects with custom methods and properties. These objects, also known as scope in AngularJS terms, work as a glue between the view and other parts ( directives, controllers and services ) inside the AngularJS application.

Whenever the AngularJS application is bootstrapped, a rootScope object is created. Each scope created by controllers, directives and services are prototypically inherited from rootScope. AngularJS documentation is one of the best resources to learn how scope inheritance works: see Scopes in AngularJS. Understanding how scope inheritance works will be useful in following sections.

Directive Types:

You can implement the following types of directives:

The restrict option is typically set to:

  • 'A' – only matches attribute name
  • 'E' – only matches element name ( by Default )
  • 'C' – only matches class name
  • 'M' – only matches comment

These restrictions can all be combined as needed:

  • 'AEC' – matches either attribute or element or class name


Link – Programmatically modify resulting DOM element instances, add event listeners, and set up data binding.

Compile – Programmatically modify the DOM template for features across copies of a directive, as when used in ng-repeat. Your compile function can also return link functions to modify the resulting element instances.

Scope inside a directive

All directives have a scope associated with them. They use this scope for accessing data/methods inside the template and link function. By default, unless explicitly set, directives don’t create their own scope. Therefore, directives use their parent scope ( usually a controller ) as their own.

However, AngularJS allows us to change the default scope of directives by passing a configuration object known as directive definition object. A directive definition object –– let’s call it as DDO –– is a simple JavaScript object used for configuring the directive’s behaviour,template..etc. Check out AngularJS docs about DDO.

scope values can be either “false”“true” or “{}” in AngularJS directive.

Different types of directive scopes

Scope : False ( Directive uses its parent scope )

There will be no scope created in DDO therefore Directive use it parent scope. Any change made on the directive scope will be reflected in parent scope and vice versa. Both Controller and Directive scope will be in sync.

Scope : true ( Directive get new  scope )

it gets its own scope by setting up scope equals to true and assigned to directive.  This newly created scope object is prototypically inherited from its parent scope ( the controller scope where it’s been used ).

Let’s see difference between setting two  scope:false and scope:true

  • When scope is set to “true”, AngularJS will create a new scope by inheriting parent scope ( usually controller scope, otherwise the application’s rootScope ). Any changes made to this new scope will not reflect back to the parent scope. However, since the new scope is inherited from the parent scope, any changes made in the Ctrtroller ( the parent scope ) will be reflected in the directive scope.
  • When scope is set to “false”, the controller Controller and directive are using the same scope object. This means any changes to the controller or directive will be in sync.

Scope : { } ( Directive gets a new isolated scope )

Till now, we saw two situations for directive scope creation. In the third type, we are going to set scope property in DDO to an Object literal. When an object literal is passed to the scope property, things are bit different. This time, there will be a new scope created for the directive, but it will not be inherited from the parent scope. This new scope also known as Isolated scope because it is completely detached from its parent scope.

  • It’ll make sure that our directive is generic, and placed anywhere inside the application. Parent scope is not going to interfere with the directive scope.

Though it’s called as an Isolated scope, AngularJS allows to communicate with the parent scope using some special symbols knows as prefixes. Because of course there are still situations where the directive needs to be able to exchange data with parent scope. The next section is dedicated to Isolated scope and its properties.

There’re 3 types of prefixes AngularJS provides.

  1.  “@” ( Text binding / one-way binding )
  2.  “=” ( Direct model binding / two-way binding )
  3.  “&” ( Behaviour binding / Method binding )
  1. The “@” prefix is a one-way binding between the directive scope and parent scope. It always expects the mapped attribute to be an expression. This is very important; because to make the “@” prefix work, we need to wrap the attribute value inside {{}}. Since “@” is creating a one-way binding between the parent and directive scope, any changes made in the parent scope will reflect inside the directive scope, but not the other way. “@” prefix is really useful when our directive needs to be initialised with some data from parent scope.
  2. Secondly we have the “=” prefix. It creates a two-way binding between the parent and directive scope. The most important point about “=” prefix is, it’ll always expect the attribute value to be the model name. That means you cannot provide an expression as the value of attribute mapped to “=” prefix. This is useful, when any of our directive scope property to be same as the parent scope property.
  3. Finally, we’re going to talk about the last prefix. The “&” prefix is also known as a method binding. This is used to bind any methods from the parent scope to the directive scope. This will be particularly useful when our directive needs to execute any callbacks in the parent scope. Look at the code to see how attribute value for the “&” prefix to be set.



AngularJS + RequireJS Example

Posted on Updated on

Prerequisite Dependency Javascripts Path –

You can download dependencies script files from below path.

Project Structure:-










HTML page for the arithmetic operation.



This is requireJS configuration file, so we defined all dependencies and javascript path.

	baseUrl: './scripts',
    shim : {
        angular: {
            exports : 'angular'

    paths: {
        "angular" : "./../lib/angular.min",
        "bootstrap" :  "/../lib/bootstrap.min",



In this file, we can add all components of AngularJS like Services, Controllers, Directive and Utility files. Since we are only using Controller file in this example so only Controller file is getting added into angular.module(…).

define(['RegisterControllers','angular'],function (RegisterControllers,angular) {

  angular.module('myApp', ['ui.controllers']);
  angular.bootstrap(document, ['myApp']);



In this Controller file, methods are defined which handle action on button clicked.

	function (angular) {

		var myCtrl = null;
		PrimaryController = function($scope){
			this.$scope = $scope;
			this.$scope.myCtrl = this;		

		PrimaryController.prototype ={
			init : function(){
        	this.$scope.message = "Hellow How are you";
           doAction : function(){
           	var num1 = this.$scope.number1;
			var num2 = this.$scope.number2;

			this.$scope.result = parseInt(num1) + parseInt(num2);

		return PrimaryController;


RegisterController.js –

Here, we register a Controller into angular.module(“ui.controllers”,[]). Also you can pass multiple controllers file path seperated by comma and assign into variables in function body then add all of them one by one in angular.module(…).controller(…).controller(..).


	function (PrimaryController,angular) {

    return angular.module("ui.controllers",[])

Finally open index.html page in your browser, we will see the below output.

Download complete code here.


What is requireJS

Posted on Updated on

What is RequireJS?

Modular Programming is used to break a large application into smaller blocks of manageable code which are always easy to maintain, readable and reusable, But it’s high cost of managing the dependencies between modules are always a major concern of developers face throughout the application development process.

So RequireJS is one of the most popular Javascript API to manage dependencies between modules and it supports AMD ( Asynchronous Module Definition  ) approach to load the modules and resolved their dependencies.

Benefits of RequireJS.

  • Easy to use and maintain than traditional ways of developing a web application.
  • Minimize the code repetition, Block of code can be easy to reused between the modules.
  • Hassle free of maintaining and keeping the scripts file in correct order.
  • Lazy loading ( Only load what you need, on demand and asynchronously )

Let’s check, how to use RequireJs

Project Hierarchy







Define an Entry point of RequireJS

First, download the latest requirejs library from here and keep it inside lib folder. Now we need to define a html file and could named index.html where RequireJS is loading as shown below.

Here, data-main is a meta attribute for requireJs that defines the initialization point of the application. it’s defined a relative path for the file where to load the RequireJS configuration.

RequireJS also assumes by default that all dependencies are scripts, so it does not expect to see a trailing “.js” suffix on module IDs. RequireJS will automatically add it when translating the module ID to a path.


Configure RequireJS

In the file app.js we defined the RequireJS config options and all files are locate under baseUrl, Since baseUrl is a current directory in this demo example but You can define the baseUrl in your application where all scripts files are placed.

How to create modules

Three modules are defined here;




Execute code RequireJS

Once, modules are defined then need to inject the dependencies and call the function.



We can see the output in the web console.





See next example of Angular+RequireJS

Hope you like it. Thanks

Configure an H2 in memory Database in Spring Boot.

Posted on

Spring Boot has great build in support for H2 database so here we will see how to configured in-memory database H2 using Spring Boot.

H2 is an open source embedded database built on java ships in a single .jar file. Therefore you can easily embed an h2 database into your application. H2 Database has a built in the web based console that you can use to interact with the database. You can use H2 database as an in-memory database, embedded database or network database. You can file more details from here.

It’s often convenient to develop applications using an in-memory embedded database. Obviously, in-memory databases do not provide persistent storage; you will need to populate your database when your application starts and be prepared to throw away data when your application ends.

First of all here are the maven dependencies for spring boot to use H2 Database. pom.xml

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">


    <description>Demo project for Spring Boot</description>

        <relativePath/> <!-- lookup parent from repository -->







Here, we created a SQL Schema file and dummy file under resource folder ( main/java/resources ), When our application gets started then it creates table and inserts into it.

sql/schema.sql file

create table User_Details (id integer not null auto_increment,
 email varchar(255),
 first_Name varchar(255),
 last_Name varchar(255),
 password varchar(255), primary key (id)

sql/data.sql file

INSERT INTO User_Details(email,first_Name,last_Name,password) VALUES ('admin@admin.com','admin','admin','admin');

INSERT INTO User_Details(email,first_Name,last_Name,password) VALUES ('rahul@gmail.com','Rahul','sharma','rahul@ku123123!');

INSERT INTO User_Details(email,first_Name,last_Name,password) VALUES ('shyam_babul@yahoo.com','Sham','babul','shyam#babul!2123');

Since Spring boot can auto configure in-memory database ( h2 ) so you don’t need to provide configuration details unless the application has been configured in other ways. If you see in below application.properties file where it has been configured from where Schema and SQL file should be picked up from resources folder.

application.properties file contains all the required configurations to connect h2 database and run Spring Boot.

# Spring Boot can auto-configured H2 database.


# Here, We create a new "local" Datasource for our application using it we can perform 'ddl' and 'dml' operations.
# Hence, it's redundant but we enabled spring data source.


Model Class

package com.spring.boot.example.domain;

public class UserDetails {

    private long id;
    private String email;
    private String first_name;
    private String last_name;
    private String password;

    public long getId() {
        return id;

    public void setId(long id) {
        this.id = id;

    public String getEmail() {
        return email;

    public void setEmail(String email) {
        this.email = email;

    public String getFirst_name() {
        return first_name;

    public void setFirst_name(String first_name) {
        this.first_name = first_name;

    public String getLast_name() {
        return last_name;

    public void setLast_name(String last_name) {
        this.last_name = last_name;

    public String getPassword() {
        return password;

    public void setPassword(String password) {
        this.password = password;

    public String toString() {
        final StringBuilder sb = new StringBuilder("UserDetails{");
        sb.append(", email='").append(email).append('\'');
        sb.append(", first_name='").append(first_name).append('\'');
        sb.append(", last_name='").append(last_name).append('\'');
        sb.append(", password='").append(password).append('\'');
        return sb.toString();

Repository Class

package com.spring.boot.example.repo;

import com.spring.boot.example.domain.UserDetails;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Repository;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

public class UserDetailsRepository {

private JdbcTemplate jdbcTemplate;

public List printUserDetailsData(){
return jdbcTemplate.query("SELECT * FROM USER_DETAILS",new UserDetailsRowMapper());

class UserDetailsRowMapper implements RowMapper{

public UserDetails mapRow(ResultSet resultSet, int i) throws SQLException {
UserDetails userDetails = new UserDetails();
return userDetails;

Main Class

package com.spring.boot.example;

import com.spring.boot.example.domain.UserDetails;
import com.spring.boot.example.repo.UserDetailsRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.jdbc.DataSourceBuilder;
import org.springframework.boot.autoconfigure.jms.JmsAutoConfiguration;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.jdbc.core.JdbcTemplate;

import javax.sql.DataSource;
import java.util.List;

@SpringBootApplication(exclude = JmsAutoConfiguration.class)
public class H2MainApp {

    public static void main(String[] args) {
        ConfigurableApplicationContext context =  SpringApplication.run(H2MainApp.class, args);
        List<UserDetails> userDetailsList = context.getBean(UserDetailsRepository.class).printUserDetailsData();
        for(UserDetails userDetails : userDetailsList){

    @ConfigurationProperties(prefix = "local.datasource")
    public DataSource getDataSource() {
        return DataSourceBuilder.create().build();

    public JdbcTemplate getJdbcTemplate(@Autowired DataSource dataSource){
        return new JdbcTemplate(dataSource);


2017-08-12 15:11:57.899 INFO 4956 — [ main] com.spring.boot.example.H2MainApp : Started H2MainApp in 7.839 seconds (JVM running for 8.638)
UserDetails{id=1, email=’admin@admin.com’, first_name=’admin’, last_name=’admin’, password=’admin’}
UserDetails{id=2, email=’rahul@gmail.com’, first_name=’Rahul’, last_name=’sharma’, password=’rahul@ku123123!’}
UserDetails{id=3, email=’shyam_babul@yahoo.com’, first_name=’Sham’, last_name=’babul’, password=’shyam#babul!2123′}

Also, H2 Web Console can be enabled by enabling these properties in application.properties. It is a convenient way to view the tables created and run queries against the in memory database.  Here is an example of the H2 database console.

Keep these properties in your application.properties to enable H2 Web Console.





How to load Profile Specific Properties files in Spring Boot

Posted on

In this articles, we will see how to load Profile specific properties files from resource directory in Spring Boot application.

Here, we set up a sample Spring Boot Project and maintains set of configuration files specific to the Profile which would be loaded when the Application runs.

Total four configuration files are created in this sample Project:-

application.properties – Which is a parent property that always loaded first before Profile specific properties file.

application.${spring.profiles.active}.properties – This is a Profile specific properties file where ${spring.profiles.active} is a placeholder of any Env i.e DEV/UAT/PROD. This property file will be loaded right after parent properties. We can keep all Profile related configuration here additionally we can overwrite derived properties of parent property file.

spring.profiles.active – Spring provides this property to enabled active Profile which you have to provide in VM argument with Environment name.






Here, we see Project setup hierarchy and configuration files created under resource folder ( /src/main/resources ).










application.properties file is parent properties file that contains all common properties which will be derived by Profile specifies properties file.

file.upload.size.limit =  1024

remote.https.enabled = false

application-dev.properties  ( When application runs on DEV Profile then load all derived properties of application.properties file as well as it own properties )


application-uat.properties ( When application runs on UAT Profile then Load and Overwrite properties value if it exists in parent properties file  )

file.upload.size.limit =  102400

remote.https.enabled = true



file.upload.size.limit =  102400

remote.https.enabled = true

PropertiesUtils.Java:- This Utilities Class load all properties file in specified order means first it loads application.properties then load Profile specifies properties ( application.${spring.profiles.active}.properties ).

 * Created by MYPC on 8/4/2017.

package com.spring.example.utils;

        import org.springframework.context.support.PropertySourcesPlaceholderConfigurer;
        import org.springframework.core.io.ClassPathResource;
        import org.springframework.core.io.Resource;

        public class PropertiesUtils {

            public static final String SPRING_PROFILES_ACTIVE = "spring.profiles.active";

            public static void initProperties() {
                String activeProfile = System.getProperty(SPRING_PROFILES_ACTIVE);
                if (activeProfile == null) {
                    activeProfile = "dev";
                PropertySourcesPlaceholderConfigurer propertySourcesPlaceholderConfigurer
                        = new PropertySourcesPlaceholderConfigurer();
                Resource[] resources = new ClassPathResource[]
                        {new ClassPathResource("application.properties"),
                                new ClassPathResource("application-" + activeProfile + ".properties")};


Finally, Main class which read all properties file and print on the Console.

package com.spring.example;

import com.spring.example.utils.PropertiesUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ConfigurableApplicationContext;

 * list
 * Created by AJAY KUMAR on 1/9/2017.
public class MainApplication {

    private long size;

    private String remoteConnectionUrl;

    private int remoteConnectionPort;

    private String remoteConnectionUsername;

    private String remoteConnectionPassword;

    private String remoteHttpsEnabled;

    private String envName;

    private String remoteConnectionAuth;

    public static void main(String[] args) {
        ConfigurableApplicationContext context = SpringApplication.run(MainApplication.class, args);
        MainApplication mainApplication = context.getBean(MainApplication.class);

    private static void printEnvironmentsProperties(MainApplication MainApplication) {
        StringBuilder stringBuilder = new StringBuilder("Properties Files ......\n");

        stringBuilder.append("env.name").append(" : ").append(MainApplication.envName).append("\n")
                .append("file.upload.size.limit").append(" : ").append(MainApplication.size).append("\n")
                .append("remote.connection.url").append(" : ").append(MainApplication.remoteConnectionUrl).append("\n")
                .append("remote.connection.port").append(" : ").append(MainApplication.remoteConnectionPort).append("\n")
                .append("remote.connection.username").append(" : ").append(MainApplication.size).append("\n")
                .append("remote.connection.password").append(" : ").append(MainApplication.remoteConnectionPassword).append("\n")
                .append("remote.connection.auth").append(" : ").append(MainApplication.remoteConnectionAuth).append("\n")
                .append("remote.https.enabled").append(" : ").append(MainApplication.remoteHttpsEnabled).append("\n");

By default, spring-profiles-active is dev Profile either you set active profile to dev or not, it loads application-dev.properties and give below output-

2017-08-05 17:37:35.068 INFO 11548 — [ main] com.spring.example.MainApplication : Started MainApplication in 4.457 seconds (JVM running for 5.036)
Properties Files ……
env.name : dev
file.upload.size.limit : 1024
remote.connection.url : localhost
remote.connection.port : 8080
remote.connection.username : 1024
remote.connection.password : Pa$$wOrd
remote.connection.auth : false
remote.https.enabled : false

When you set spring-profiles-active is PROD  in VM options then you will get below output.

2017-08-05 17:41:06.539 INFO 10184 — [ main] com.spring.example.MainApplication : Started MainApplication in 4.095 seconds (JVM running for 4.783)
Properties Files ……
env.name : PROD
file.upload.size.limit : 102400
remote.connection.url :
remote.connection.port : 9090
remote.connection.username : 102400
remote.connection.password : Pa$$wOrd@233$
remote.connection.auth : true
remote.https.enabled : true

I hope this article would be helpful!! Thanks.

ThreadLocal Example with Java 8

Posted on Updated on

What is ThreadLocal in Java?

ThreadLocal is a specially provisioned functionality by JVM to provide an isolated storage space for threads only. like the value of instance scoped variable are bound to a given instance of a class only. each object has its only values and they can not see each other value. so is the concept of ThreadLocal variables, they are local to the thread in the sense of object instances other thread except for the one which created it, can not see it.

Like request, session and application scope of any Object, We can define a Thread Scope of any Object thus Object visibility would be only within the Thread and Every Thread has it execution life cycle, After a thread goes away, all of its copies of thread-local instances are subject to garbage collection (unless other references to these copies exist).

Although we usually create a Synchronize  Object for Thread safety in MultiThread application therefore only one Thread can be obtained a monitor to access shared Object Since shared Object is not thread safe.

In Java 8, A new method is introdued  to determine the initial value.

public static <S> ThreadLocal<S> withInitial(Supplier<? extends S> supplier) {
    return new SuppliedThreadLocal<>(supplier);

Here, a simple ThreadLocal example of Java 8 is demonstrated that how each Thread gets own ThreadLocal copy of variable and value remain same even in Iteration process and each thread are executing separately on the ThreadLocal variable.


import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.IntStream;

 * Created by MYPC on 5/29/2017.
public class ThreadLocalExample {
    private static final AtomicInteger transactionId = new AtomicInteger(10000);
    private static final ThreadLocal threadLocal = ThreadLocal.withInitial(() -> transactionId.getAndIncrement());

    public static void main(String[] args) {

        // Thread 1 executing and getting same Transaction Id for all iteration
        new Thread(() -> IntStream.range(0, 3).forEach(val -> {
            System.out.println(Thread.currentThread().getName() + " > " + threadLocal.get());

        // Thread 2 executing and getting same Transaction Id for all iteration
        new Thread(() -> IntStream.range(0, 3).forEach(val -> {
            System.out.println(Thread.currentThread().getName() + " > " + threadLocal.get());
        // Thread 3 executing and getting same Transaction Id for all iteration
        new Thread(() -> IntStream.range(0, 3).forEach(val -> {
            System.out.println(Thread.currentThread().getName() + " > " + threadLocal.get());

Execution Output :-

Thread-1 > 10001
Thread-1 > 10001
Thread-1 > 10001
Thread-0 > 10000
Thread-0 > 10000
Thread-0 > 10000
Thread-2 > 10002
Thread-2 > 10002
Thread-2 > 10002

Java 8 : How to calculate difference between two Dates.

Posted on





Java 8 introduced Date and Time API that represents the principle date-time concepts, including instants, durations, dates, times, timezones and periods. They are also based on the ISO Calendar system and unlike their predecessor, class in java.time packages are both immutable and thread-safe. New date and time API is located inside java.time package and some of the key classes are following :


  • Instant – It represents a timestamp
  • LocalDate – a date without time e.g. 2014-01-14. It can be used to store birthday, anniversary, date of joining etc.
  • LocalTime – represents time without a date
  • LocalDateTime – is used to combine date and time, but still without any offset or time-zone
  • ZonedDateTime – a complete date-time with time-zone and resolved offset from UTC/Greenwich



Below are the complete example of calculating seconds/minutes/hours/week between two given dates alone with JUtil Testcase.

package com.example1;

import java.time.DayOfWeek;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.temporal.ChronoUnit;
import java.util.List;
import java.util.stream.Stream;

 * Created by MYPC on 1/15/2017.
public class DateUtils {

     * Calculated Nos of Days between given two Date.
     * @param startDate
     * @param endDate
     * @return
    public static long DaysBetween(LocalDate startDate, LocalDate endDate) {
        return ChronoUnit.DAYS.between(startDate, endDate);

     * Calculated Nos. of hours between given two Date.
     * @param startDate
     * @param endDate
     * @return
    public static long HoursBetween(LocalDateTime startDate, LocalDateTime endDate) {
        return ChronoUnit.HOURS.between(startDate, endDate);

     * Calculated Nos. of Minutes between given two Date
     * @param startDate
     * @param endDate
     * @return
    public static long MinsBetween(LocalDateTime startDate, LocalDateTime endDate) {
        return ChronoUnit.MINUTES.between(startDate, endDate);

     * Calculated Nos. of Seconds between given two Date
     * @param startDate
     * @param endDate
     * @return
    public static long SecondsBetween(LocalDateTime startDate, LocalDateTime endDate) {
        return ChronoUnit.SECONDS.between(startDate, endDate);

     * Calculated Nos. of weeks between given two Date
     * @param startDate
     * @param endDate
     * @return
    public static long WeeksBetween(LocalDate startDate, LocalDate endDate) {
        return ChronoUnit.WEEKS.between(startDate, endDate);

     * It will return days between two Dates with excluding given days in ignore list.
     * and return calculated Days between which is not included the end Date.
     * Example :-
     * LocalDate startDate = LocalDate.parse("2017-01-01", DateTimeFormatter.ofPattern("yyyy-MM-dd"));
     * LocalDate endDate = LocalDate.parse("2017-01-15", DateTimeFormatter.ofPattern("yyyy-MM-dd"));
     * System.out.println(DaysBetween(startDate,endDate,Stream.of(DayOfWeek.SATURDAY,DayOfWeek.SUNDAY).collect(Collectors.toList())));
     * @param startDate
     * @param endDate
     * @param skipDays
     * @return
    public static long DaysBetween(LocalDate startDate, LocalDate endDate, List skipDays) {
        return Stream.iterate(startDate, d -> d.plusDays(1))
                .limit(startDate.until(endDate, ChronoUnit.DAYS))
                .filter(d -> !skipDays.contains(d.getDayOfWeek()))

JUnit test

package com.example1;

import org.junit.Assert;
import org.junit.Test;

import java.time.DayOfWeek;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.Month;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;

 * Created by MYPC on 1/15/2017.
public class DateUtilsTest {

    LocalDate startDate = LocalDate.of(2017, Month.JANUARY, 01);
    LocalDate endDate = LocalDate.of(2017, Month.JANUARY, 15);

    LocalDateTime startDt = LocalDateTime.now().minusHours(23);
    LocalDateTime endDt = LocalDateTime.now();

    public void DaysBetweenDateTest() {
        Assert.assertEquals(DateUtils.DaysBetween(startDate, endDate), 14);

    public void HoursBetweenDateTest() {
        Assert.assertEquals(DateUtils.HoursBetween(startDt, endDt), 23);

    public void MinutesBetweenDateTest() {
        Assert.assertEquals(DateUtils.MinsBetween(startDt, endDt), 1380);

    public void SecondsBetweenDateTest() {
        Assert.assertEquals(DateUtils.SecondsBetween(startDt, endDt), 82800);

    public void WeeksBetweenDateTest() {
        Assert.assertEquals(DateUtils.WeeksBetween(startDate, endDate), 2);

    public void DaysBetweenDateByIgnoreSundayAndSaturdayTest() {
        List ignoreDays = Stream.of(DayOfWeek.SATURDAY, DayOfWeek.SUNDAY).collect(Collectors.toList());
        Assert.assertEquals(DateUtils.DaysBetween(startDate, endDate, ignoreDays), 10);

Testcases snapshots here :-