Java Date – Java2Blog https://java2blog.com A blog on Java, Python and C++ programming languages Tue, 29 Nov 2022 06:30:03 +0000 en-US hourly 1 https://wordpress.org/?v=6.2.9 https://java2blog.com/wp-content/webpc-passthru.php?src=https://java2blog.com/wp-content/uploads/2022/09/cropped-ICON_LOGO_TRANSPARENT-32x32.png&nocache=1 Java Date – Java2Blog https://java2blog.com 32 32 Check if Date Is Between Two Dates in Java https://java2blog.com/check-if-date-is-between-two-dates-java/?utm_source=rss&utm_medium=rss&utm_campaign=check-if-date-is-between-two-dates-java https://java2blog.com/check-if-date-is-between-two-dates-java/#respond Sat, 26 Nov 2022 16:07:44 +0000 https://java2blog.com/?p=21152 Introduction

In this article, we will discuss and dwell on how to compare dates in Java. The problem statement is : Check if a Date is between two dates in Java. This roughly translates to Given a date, we need to check if it lies between the range of two dates. Let us understand this with a sample input example.

Input:

Date_1 : 21/10/18

Date_2 : 22/11/18

Date to Validate: 13/11/18

Output:

The date 13/11/18 lies between the dates 21/10/18 and 22/11/18

We will discuss different solutions to this problem in great depth and detail to make it captivating. Let us first have a quick look at how Dates are represented in Java.

Date & Local Date Class in Java

In Java, we can represent Dates as text in a Stringtype variable. But using a String would make formatting the date for different operations very resilient. So, to avoid this Java provides the Date and LocalDate class to perform operations on a Date meta type easily.

Date Class in Java

It is present in java.util package. We can create a date of any format (DD/MM/YYYYY, MM/DD/YYYY, YYYY/MM/DD, etc.) using the SimpleDateFormat class and instantiate it to a Date class object using the parse() method of the SimpleDateFormat class.

LocalDate class in Java

It is present in java.time package. We can create a date of only a specific format i.e. YYYY-MM-DD. We instantiate the LocalDate object using the of() method and pass the relevant parameters to it.

We can also create a LocalDate object using the parse() method where we need to pass the required Date as a String in the format YYYY-MM-DD.

Let us see the sample code to create custom dates using the classes above. It is important to get an idea as we will look at more examples related to this.

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.util.Date;

public class DateExamples {

    public static void main(String[] args) throws ParseException {

        // Date class example
        // Create a SimpleDateFormat reference with different formats
        SimpleDateFormat sdf1 = new SimpleDateFormat("dd/MM/yyyy");
        SimpleDateFormat sdf2 = new SimpleDateFormat("yyyy/MM/dd");

        //Create date with format dd/mm/yyyy
        Date t1 = sdf1.parse("21/12/2018");
        //Create date with format yyyy/mm/dd
        Date t2 = sdf2.parse("2019/11/11");
        //Print the dates using the format() method     
        System.out.println("-----------Date Class Example -------------");
        System.out.println(t1);
        System.out.println(sdf1.format(t1));
        System.out.println();
        System.out.println(t2);
        System.out.println(sdf2.format(t2));

        // LocalDate class example
        // Create using of() method.
        LocalDate ld1 = LocalDate.of(2021, 10, 30);
        // Create using  parse() method
        LocalDate ld2 = LocalDate.parse("2010-12-20");
        System.out.println("-----------LocalDate Class Example -----------");
        System.out.println(ld1);
        System.out.println(ld2);

    }
}

-----------Date Class Example -------------
Fri Dec 21 00:00:00 IST 2018
21/12/2018

Mon Nov 11 00:00:00 IST 2019
2019/11/11
-----------LocalDate Class Example -----------
2021-10-30
2010-12-20

Check if The Date Is Between Two Dates in Java

Now, we outline different approaches for the solution to this problem. For some of the approaches, we will undertake the Date values only in the format: DD/MM/YYYY. However, it will support other date formats.

Using the isAfter() and isBefore() Methods of the Local Date Class in Java

The LocalDate class in Java provides the isAfter() method to check if a date lies after the given date and the isBefore() method to check if the date lies before. We call these methods with the date to check and pass the argument date.

We can combine these two methods to Check if a date is between two given dates.

Important points to note:

  • We will take three variables startDate, endDate, and dateToValidate as LocalDate instances and create them using the of() method.
  • We check if the dateToValidate lies after the startDate and if dateToValidate lies before the endDate. If the condition satisfies we print the date is validated.
  • We call the isAfter() and isBefore() methods with the dateToValidate object providing the start and end dates respectively to ensure the check.

Let us look at the code for this approach.

import java.time.LocalDate; 

public class CheckDateBetweenLocalDateMain {

    public static void main(String[] args) throws ParseException {

        //Create the Lower and Upper Bound Local Date 
                //Format: YYYY-MM-DD
        LocalDate startDate = LocalDate.of(2018, 9, 21);
        LocalDate endDate = LocalDate.of(2018, 10, 22);

        //Create the date object to check
        LocalDate dateToValidate = LocalDate.of(2018, 10, 13);

        //Use the isAfter() and isBefore() method to check date
        if(dateToValidate.isAfter(startDate) && dateToValidate.isBefore(endDate))
        {
			System.out.println("The date "+dateToValidate+" lies between the two dates");
        }
        else
        {
			System.out.println(dateToValidate+" does not lie between the two dates");
        }
    }
}

The date 2018-10-13 lies between the two dates

If we need to include the endpoints of the start dates and end dates respectively, we can replace the if condition with this line of code:

if(!(dateToValidate.isAfter(endDate) || dateToValidate.isBefore(startDate)))

Using the compareTo() Method of the Local Date Class in Java

The LocalDate class in Java provides the compareTo() method with which we can compare dates easily based on the return value. Here, we can use this method to Check if the date lies between two dates.

The syntax of the method:

public int compareTo(Date anotherDate)

The compareTo() method has the following restrictions:

  • It returns the value 0 if the argument anotherDate is equal to this Date.
  • It returns value < 0 (i.e. -1) if this Date is before the anotherDate argument.
  • It returns a value > 0 (i.e. +1) if this Date is after the anotherDate argument.

Important points to note:

  • We compare the startDate with the dateToValidate and the dateToValidate with the endDate.
  • It returns values +1(if greater) or -1(if smaller) based on the comparison. We then multiply the returned values from both expressions.
  • If the resultant value is greater than 0 it means the date lies within the range otherwise it is not valid.

Let us look at the code.

import java.time.LocalDate;

public class CheckDateBetweenLocalDateMain {

public static void main(String[] args) {

      //Create the Lower and Upper Bound Date object
      LocalDate startDate = LocalDate.of(2019,7,18);
      LocalDate endDate = LocalDate.of(2019,12,28);

      //Create the date object to check
      LocalDate dateToValidate = LocalDate.of(2019,8,25);

      //Compare each date and multiply the returned values
      if(startDate.compareTo(dateToValidate) * dateToValidate.compareTo(endDate) > 0)
      {
        System.out.println("The date "+dateToValidate+" lies between the two dates");
      }
      else
      {
        System.out.println(dateToValidate+" does not lie between the two dates");
      }
	}
}

Output:

The date 2019-8-25 lies between the two dates

Using the after() and before() Methods of the Date Class in Java

The Date class in Java provides the after() method to check if a date lies after the given date and the before() method to check if the date lies before. We can combine these two methods to Check if a date is between two dates.

Important points to note:

  • We will take three variables startDate, endDate, and dateToValidate as Date objects using the parse() method of SimpleDateFormat class.
  • We check if the dateToValidate lies after the startDate and if dateToValidate lies before the endDate. If the condition satisfies we print the date is validated.
  • We call the after() and before() methods with the dateToValidate object providing the start and end dates respectively to ensure the check.

Note: The parse() method of SimpleDateFormat throws ParseException so ensure that the throws declaration is given in the calling method or implemented.

Let us look at the code snippet for this approach.

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

public class CheckDateBetweenTwoDatesMain {

    public static void main(String[] args) throws ParseException {

        // Create a SimpleDateFormat reference with different formats
        SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");

        //Create the Lower and Upper Bound Date object
        Date startDate = sdf.parse("21/10/2018");
        Date endDate = sdf.parse("22/11/2018");

        //Create the date object to check
        Date dateToValidate = sdf.parse("13/11/2018");

        //Use the after() and before() method to check date
        if(dateToValidate.after(startDate) && dateToValidate.before(endDate))
        {
            System.out.println("The date "+sdf.format(dateToValidate)+" lies between the two dates");
        }
        else
        {
			System.out.println(sdf.format(dateToValidate)+" does not lie between the two dates");
        }
    }
}

Output:

While validating, If we need to include the endpoints of the start dates and end dates respectively, we can replace the if condition with this line of code:

if(!(dateToValidate.after(endDate) || dateToValidate.before(startDate)))

Using the compare To() Method of the Date Class in Java

Similar to the LocalDate class, the Date class in Java also provides the compareTo() method which we can use to compare dates easily and Check if the date lies between two dates.

The syntax of the method:

public int compareTo(Date anotherDate)

The compareTo() method has the same restrictions as discussed above for the LocalDate class.

Important points to note:

  • We compare the startDate with the dateToValidate and the dateToValidate with the endDate.
  • It returns values +1(if greater) or -1(is smaller) based on the comparison. We then multiply the returned values from both expressions.
  • If the value is greater than 0 it means the date lies within the range otherwise it is not valid.

Let us look at the code snippet for this approach as well.

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

public class CheckDateBetweenTwoDatesMain {

public static void main(String[] args) throws ParseException {

      // Create a SimpleDateFormat reference with different formats
      SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");

      //Create the Lower and Upper Bound Date object
      Date startDate = sdf.parse("11/07/2019");
      Date endDate = sdf.parse("30/12/2019");

      //Create the date object to check
      Date dateToValidate = sdf.parse("22/08/2019");
      //Compare each date and multiply the returned values
      if(startDate.compareTo(dateToValidate) * dateToValidate.compareTo(endDate) > 0)
      {
        System.out.println("The date "+sdf.format(dateToValidate)+" lies between the two dates");
      }
      else
      {
        System.out.println(sdf.format(dateToValidate)+" does not lie between the two dates");
      }
 }
}

Output:

Using the getTime() Method of The Date Class in Java

We can also use the getTime() method of the Date class to check if the date is between two dates. The getTime() method converts a Date into its equivalent milliseconds since January 1, 1970. The return value is of type Long.

There are two ways we can solve this using the getTime() method:

  1. We can compute the total millisecond value for each of the dates and compare the dateToValidate with the startDate and endDate respectively.
  2. To validate the dates, we can subtract the millisecond value of dateToValidate with and from the start and end dates respectively.

Note: This approach would not work as expected if we compare dates before January 1, 1970. In such case, the getTime() method will give a negative value on crossing the Long limit.

Let us look at the implementation of these approaches in code.

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

public class CheckDateUsingGetTimeMain {

    public static void main(String[] args) throws ParseException {

        // Create a SimpleDateFormat reference with different formats
        SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");

        //Create the Lower and Upper Bound Date object
        Date startDate = sdf.parse("11/07/2019");
        Date endDate = sdf.parse("30/12/2019");

        //Create the date object to check
        Date dateToValidate = sdf.parse("22/08/2019");

        // Using getTime() method to get each date in milliseconds
        long startDateInMillis = startDate.getTime();
        long endDateInMillis = endDate.getTime();
        long dateInMillis = dateToValidate.getTime();

        // Approach 1: Comparing the millisecond value of each date.
        if(startDateInMillis <= dateInMillis && dateInMillis <= endDateInMillis )
        {
			System.out.println("The date "+sdf.format(dateToValidate)+" lies between the two dates\n");
        }
        else
        {
			System.out.println(sdf.format(dateToValidate)+" does not lie between the two dates\n");
        }

        // Approach 2: Subtracting the millisecond values of each date  
        // Create new date to check
        dateToValidate = sdf.parse("21/08/2017");
        dateInMillis = dateToValidate.getTime();

        if(dateInMillis - startDateInMillis >=0 && endDateInMillis - dateInMillis >= 0 )
        {
			System.out.println("The date "+sdf.format(dateToValidate)+" lies between the two dates");   
        }
        else
        {
			System.out.println(sdf.format(dateToValidate)+" does not lie between the two dates");   
        }

    }
}

Output:

Using the Joda-Time Library

Before Java 8, The legacy date and time classes in Java were equipped poorly with minimal utilities. The Joda-Time provides a quality replacement for these Java Date and Time classes. Here, to Check if the date lies between two dates we can use the inbuilt functionality of this package.

We can use the DateTime class and its utility methods of the JodaTime Library by importing with the following maven dependency.

<dependency>
    <groupId>joda-time</groupId>
    <artifactId>joda-time</artifactId>
    <version>2.1</version>
</dependency>

For ease, we will use the JAR file component of the Joda-Time package in our code. You can download the Joda-Time Library JAR from the embedded link. Now, let us look into the steps.

  • We will create three instances of the DateTime class initializing it with the Date objects startDate, endDate, and dateToValidate respectively.
  • The DateTime class provides the isAfter() and isBefore() utility methods, we then compare the Datetime instance of dateToValidate Date object and validate the same using these methods.

Let us have a quick look at the implementation of this approach as well.

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

import org.joda.time.DateTime;

public class CheckDateJodaTime {

    public static void main(String[] args) throws ParseException {

        // Create a SimpleDateFormat reference with different formats
        SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");

        //Create the Lower and Upper Bound Date object
        Date startDate = sdf.parse("11/07/2019");
        Date endDate = sdf.parse("30/12/2019");

        //Create the date object to check
        Date dateToValidate = sdf.parse("22/08/2019");

        // Create Joda Datetime instance using Date objects
        DateTime dateTime1 = new DateTime(startDate);
        DateTime dateTime2 = new DateTime(endDate);
        DateTime dateTime3 = new DateTime(dateToValidate);

        // compare datetime3 with datetime1 and datetime2 using the methods
        if(( dateTime3.isAfter( dateTime1 ) ) && ( dateTime3.isBefore( dateTime2 ) ))
        {
			System.out.println("The date "+sdf.format(dateToValidate)+" lies between the two dates\n");
        }
        else
        {
			System.out.println(sdf.format(dateToValidate)+" does not lie between the two dates\n");
        }

    }
}

Output:

Using the Apache Commons Net Library – Time Stamp Class

The Apache Commons API provides powerful and reusable Java components and dependencies that we can embed into our applications and programs. Here, to check if the Date lies between two dates we can use the inbuilt functionality of this package.

We can use the TimeStamp class of the Net package of Apache Commons Library by importing with the following maven dependency.

<dependency>
  <groupId>commons-net</groupId>
  <artifactId>commons-net</artifactId>
  <version>3.8.0</version>
</dependency>

For ease, we will use the JAR file component of the Apache Commons Net package in our code. We can download the Apache Commons Net JAR to set up the JAR file component for this package.

Now, let us look into the steps:

  • We will create three instances of the TimeStamp class initializing it with the Date objects startDate, endDate, and dateToValidate respectively.
  • For each TimeStamp object that we create, we calculate the total seconds using the getSeconds() method.
  • The getseconds() calculates the total seconds from the given date to the present date and returns the value of type long.
  • Then compare the total second value of the TimeStamp instance of dateToValidate with other dates and validate it.

Let us look at the implementation of the approach in code.

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

import org.apache.commons.net.ntp.TimeStamp;

public class CheckDateApacheCommon {

    public static void main(String[] args) throws ParseException {

        // Create a SimpleDateFormat reference with different formats
        SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");

        //Create the Lower and Upper Bound Date object
        Date startDate = sdf.parse("11/07/2019");
        Date endDate = sdf.parse("30/12/2019");

        //Create the date object to check
        Date dateToValidate = sdf.parse("22/08/2019");

        // Create TimeStamp instance using Date objects
        TimeStamp ts1 = new TimeStamp(startDate);
        TimeStamp ts2 = new TimeStamp(endDate);
        TimeStamp ts3 = new TimeStamp(dateToValidate);

        // Get the total seconds value for each date
        long time1 = ts1.getSeconds();
        long time2 = ts2.getSeconds();
        long time3 = ts3.getSeconds();

        // compare time3 with time1 and time2
        if( time1 < time3 && time3 < time2 )
        {
			System.out.println("The date "+sdf.format(dateToValidate)+" lies between the two dates\n");
        }
        else
        {
			System.out.println(sdf.format(dateToValidate)+" does not lie between the two dates\n");
        }

    }
}

Output:

That’s all for the article, we discussed 7 ways to Check if a Date lies between two dates in java in detail with code and working examples. You can try these examples out in your Local IDE for a clear understanding.

Feel free to reach out to us for any queries/suggestions.

]]>
https://java2blog.com/check-if-date-is-between-two-dates-java/feed/ 0
Find Difference Between Two Instant in Java https://java2blog.com/find-difference-between-two-instant-java/?utm_source=rss&utm_medium=rss&utm_campaign=find-difference-between-two-instant-java https://java2blog.com/find-difference-between-two-instant-java/#respond Wed, 05 Oct 2022 12:13:55 +0000 https://java2blog.com/?p=20929 In this post, we will see how to find difference between two Instant in Java.

Ways to find difference between two Instant in Java

There are multiple ways to find difference between two Instant in various time units such as Days, Hours, Minutes, Seconds etc.

Using Instant’s until() method

To find difference between two Instant, We can use Instant’s until() method.

Instant’s until() method returns amount of time with another date in terms of specified unit. You can pass specific TemporalUnit such as DAYS, SECONDS to get result in specified units.

For example:
If you want amount of seconds between two Instant, you can use below code:

long noOfSeconds = instantBefore.until(instantAfter, ChronoUnit.SECONDS);

Here is an example:

package org.arpit.java2blog;

import java.time.Instant;
import java.time.temporal.ChronoUnit;

public class DifferenceBetweenTwoInstantUntil {
    public static void main(String[] args) {
        Instant instantBefore = Instant.parse("2022-09-14T18:42:00Z");
        Instant instantAfter = Instant.parse("2022-09-16T05:25:00Z");

        long noOfDays = instantBefore.until(instantAfter, ChronoUnit.DAYS);
        long noOfHours = instantBefore.until(instantAfter, ChronoUnit.HOURS);
        long noOfMinutes = instantBefore.until(instantAfter, ChronoUnit.MINUTES);
        long noOfSeconds = instantBefore.until(instantAfter, ChronoUnit.SECONDS);

        System.out.println("Days: "+noOfDays);
        System.out.println("Hours: "+noOfHours);
        System.out.println("Minutes: "+noOfMinutes);
        System.out.println("Seconds: "+noOfSeconds);
    }
}

Output

Days: 1
Hours: 34
Minutes: 2083
Seconds: 124980

Using ChronoUnit Enum

We can use ChronoUnit method to find difference between two Instant.

It intenally calls until() method to find the difference between two time units.

For example:
If you want amount of seconds between two Instant, we can use following syntax:

long noOfSeconds = ChronoUnit.SECONDS.between(instantBefore,instantAfter);

Here is an example:

package org.arpit.java2blog;

import java.time.Instant;
import java.time.temporal.ChronoUnit;

public class DifferenceBetweenTwoInstant {
    public static void main(String[] args) {
        Instant instantBefore = Instant.parse("2022-09-14T18:42:00Z");
        Instant instantAfter = Instant.parse("2022-09-16T05:25:00Z");

        long noOfDays = ChronoUnit.DAYS.between(instantBefore, instantAfter);
        long noOfHours = ChronoUnit.HOURS.between(instantBefore,instantAfter);
        long noOfMinutes = ChronoUnit.MINUTES.between(instantBefore,instantAfter);
        long noOfSeconds = ChronoUnit.SECONDS.between(instantBefore,instantAfter);

        System.out.println("Days: "+noOfDays);
        System.out.println("Hours: "+noOfHours);
        System.out.println("Minutes: "+noOfMinutes);
        System.out.println("Seconds: "+noOfSeconds);
    }
}

Output

Days: 1
Hours: 34
Minutes: 2083
Seconds: 124980

Using Duration’s between() method

We can use Duration’s between() method to find difference between two Instant.

Duration’s between() method returns amount of time with another date in terms of minutes, hours, seconds and nanoseconds. You can use toXXX() method to convert into required unit.

For example:
If you want amount of seconds between two Instant, we can use following syntax:

long noOfSeconds = Duration.between(instantBefore, instantAfter).toSeconds();

Here is an example:

package org.arpit.java2blog;

import java.time.Duration;
import java.time.Instant;

public class DifferenceBetweenTwoInstantDuration {
    public static void main(String[] args) {
        Instant instantBefore = Instant.parse("2022-09-14T18:42:00Z");
        Instant instantAfter = Instant.parse("2022-09-16T05:25:00Z");

        long noOfDays = Duration.between(instantBefore, instantAfter).toDays();
        long noOfHours = Duration.between(instantBefore, instantAfter).toHours();
        long noOfMinutes = Duration.between(instantBefore, instantAfter).toMinutes();
        long noOfSeconds = Duration.between(instantBefore, instantAfter).toSeconds();

        System.out.println("Days: "+noOfDays);
        System.out.println("Hours: "+noOfHours);
        System.out.println("Minutes: "+noOfMinutes);
        System.out.println("Seconds: "+noOfSeconds);
    }
}

Output

Days: 1
Hours: 34
Minutes: 2083
Seconds: 124980

That’s all about how to find difference two Instant in Java.

]]>
https://java2blog.com/find-difference-between-two-instant-java/feed/ 0
Find Difference Between Two LocalDate in Java https://java2blog.com/find-difference-between-two-localdate-java/?utm_source=rss&utm_medium=rss&utm_campaign=find-difference-between-two-localdate-java https://java2blog.com/find-difference-between-two-localdate-java/#respond Wed, 05 Oct 2022 10:03:21 +0000 https://java2blog.com/?p=20914 In this post, we will see how to find difference between two LocalDate in Java.

Ways to find difference between two LocalDate in Java

There are multiple ways to find difference between two LocalDate in various time units such as Days, Months, Years etc.

Using LocalDate’s until() method

We can use LocalDate’s until() method to find difference between two LocalDate.

LocalDate’s until() method returns amount of time with another date in terms of given unit. You can pass specific TemporalUnits such as MONTHS, DAYS to get result in specified units.

For example:
If you want amount of days between two LocalDate, we can use following syntax:

startDate.until(endDate, DAYS)

Here is an example:

package org.arpit.java2blog;

import java.time.LocalDate;
import java.time.Month;
import java.time.temporal.ChronoUnit;

public class DifferenceBetweenTwoLocalDateUntil {
    public static void main(String[] args) {
        LocalDate dateBefore = LocalDate.of(2022, Month.AUGUST, 23);
        LocalDate dateAfter = LocalDate.of(2022, Month.DECEMBER, 25);

        long noOfYears = dateBefore.until(dateAfter, ChronoUnit.YEARS);
        long noOfMonths = dateBefore.until(dateAfter, ChronoUnit.MONTHS);
        long noOfWeeks = dateBefore.until(dateAfter, ChronoUnit.WEEKS);
        long noOfDays = dateBefore.until(dateAfter, ChronoUnit.DAYS);

        System.out.println("Years: "+noOfYears);
        System.out.println("Months: "+noOfMonths);
        System.out.println("Weeks: "+noOfWeeks);
        System.out.println("Days: "+noOfDays);
    }
}

Output

Years: 0
Months: 4
Weeks: 17
Days: 124

Using ChronoUnit Enum

We can use ChronoUnit method to find difference between two LocalDate.

It intenally calls until() method to find the difference between to time unit.

For example:
If you want amount of days between two LocalDate, we can use following syntax:

ChronoUnit.YEARS.between(dateBefore, dateAfter);

Here is an example:

package org.arpit.java2blog

import java.time.LocalDate;
import java.time.Month;
import java.time.temporal.ChronoUnit;

public class DifferenceBetweenTwoLocalDateChronoUnit {
    public static void main(String[] args) {
        LocalDate dateBefore = LocalDate.of(2022, Month.AUGUST, 23);
        LocalDate dateAfter = LocalDate.of(2022, Month.DECEMBER, 25);

        long noOfYears = ChronoUnit.YEARS.between(dateBefore, dateAfter);
        long noOfMonths = ChronoUnit.MONTHS.between(dateBefore, dateAfter);
        long noOfWeeks = ChronoUnit.WEEKS.between(dateBefore, dateAfter);
        long noOfDays = ChronoUnit.DAYS.between(dateBefore, dateAfter);

        System.out.println("Years: "+noOfYears);
        System.out.println("Months: "+noOfMonths);
        System.out.println("Weeks: "+noOfWeeks);
        System.out.println("Days: "+noOfDays);
    }
}

Output

Years: 0
Months: 4
Weeks: 17
Days: 124

Using Duration’s between() method

We can use Duration’s between() method to find difference between two LocalDate.

Duration’s between() method returns amount of time with another date in terms of minutes, hours, seconds and nanoseconds. You can use toXXX() method to convert into required unit.

For example:
If you want amount of days between two LocalDate, we can use following syntax:

Duration.between(dateBefore.atStartOfDay(), dateAfter.atStartOfDay()).toHours();

Here is an example:

package org.arpit.java2blog;

import java.time.Duration;
import java.time.LocalDate;
import java.time.Month;

public class DifferenceBetweenTwoLocalDateDuration {
    public static void main(String[] args) {
        LocalDate dateBefore = LocalDate.of(2022, Month.AUGUST, 23);
        LocalDate dateAfter = LocalDate.of(2022, Month.DECEMBER, 25);

        long noOfDays = Duration.between(dateBefore.atStartOfDay(), dateAfter.atStartOfDay()).toDays();
        long noOfHours = Duration.between(dateBefore.atStartOfDay(), dateAfter.atStartOfDay()).toHours();
        long noOfMinutes = Duration.between(dateBefore.atStartOfDay(), dateAfter.atStartOfDay()).toMinutes();
        long noOfSeconds = Duration.between(dateBefore.atStartOfDay(), dateAfter.atStartOfDay()).toSeconds();

        System.out.println("Days: "+noOfDays);
        System.out.println("Hours: "+noOfHours);
        System.out.println("Minutes: "+noOfMinutes);
        System.out.println("Seconds: "+noOfSeconds);
    }
}

Output

Days: 124
Hours: 2976
Minutes: 178560
Seconds: 10713600

Using Period’s between() method

We can use Period’s between() method to find difference between two LocalDate.

Period’s between() method date based amount of time in the ISO-8601 calendar system, such as 3 years, 8 months and 5 days. This class provide output in terms of years, months and days.

  • Start date is included, but end date is excluded
  • It can return negative result if end date is before start date.

As Period class represents time in terms of format a years, b months and c days, so when you call getDays() method on period object, it returns c days part only.

Here is an example:

package org.arpit.java2blog;

import java.time.LocalDate;
import java.time.Month;
import java.time.Period;

public class DifferenceBetweenTwoLocalDatePeriod {
    public static void main(String[] args) {
        LocalDate localDate1 = LocalDate.of(1999, Month.AUGUST, 23);
        LocalDate localDate2 = LocalDate.of(2022, Month.DECEMBER, 25);

        Period period = Period.between(localDate1, localDate2);

        System.out.print(period.getYears() + " years,");
        System.out.print(period.getMonths() + " months,");
        System.out.print(period.getDays() + " days");
    }
}

Output

23 years,4 months,2 days

Frequently asked questions

How to find difference between two LocalDate in Java in Days?

You can use DAYS‘s between method to get difference between two LocalDate in Java. It is exact same method as ChronoUnit enum, only difference is to use import static to directly import the java.time.temporal.ChronoUnit.DAYS.

package org.arpit.java2blog;

import java.time.LocalDate;
import java.time.Month;
import static java.time.temporal.ChronoUnit.DAYS;

public class DifferenceBetweenTwoLocalDateDays {
    public static void main(String[] args) {
        LocalDate beforeDate = LocalDate.of(2022, Month.AUGUST, 23);
        LocalDate afterDate = LocalDate.of(2022, Month.DECEMBER, 25);

        long noOfDays = DAYS.between(beforeDate, afterDate);
        System.out.println("Days: "+noOfDays);
    }
}

Output

Days: 124

How to find difference between two LocalDate in Java in Years?

You can use YEARS‘s between method to get difference between two LocalDate in Java. It is exact same method as ChronoUnit enum, only difference is to use import static to directly import the java.time.temporal.ChronoUnit.YEARS.

package org.arpit.java2blog;

import java.time.LocalDate;
import java.time.Month;

import static java.time.temporal.ChronoUnit.YEARS;

public class DifferenceBetweenTwoLocalDateDays {
    public static void main(String[] args) {
        LocalDate beforeDate = LocalDate.of(1999, Month.AUGUST, 23);
        LocalDate afterDate = LocalDate.of(2022, Month.DECEMBER, 25);

        long noOfYears = YEARS.between(beforeDate, afterDate);
        System.out.println("YEARS: "+noOfYears);
    }
}

Output

YEARS: 23

How to find difference between two LocalDate in Java in Months?

You can use MONTHS‘s between method to get difference between two LocalDate in Java. It is exact same method as ChronoUnit enum, only difference is to use import static to directly import the java.time.temporal.ChronoUnit.MONTHS.

package org.arpit.java2blog;

import java.time.LocalDate;
import java.time.Month;
import static java.time.temporal.ChronoUnit.MONTHS;

public class DifferenceBetweenTwoLocalDateMonths {
    public static void main(String[] args) {
        LocalDate beforeDate = LocalDate.of(2022, Month.AUGUST, 23);
        LocalDate afterDate = LocalDate.of(2022, Month.DECEMBER, 25);

        long noOfMonths = MONTHS.between(beforeDate, afterDate);
        System.out.println("Months: "+noOfMonths);
    }
}

Output

Months: 4

How to find difference between two LocalDate in Java in Hours?

You can use Duration‘s between method to get difference between two LocalDate in Java. You need to call LocalDate‘s atStartOfDay() method to convert LocalDate to LocalDateTime and use it Duration‘s between() method. Call toHours() to get desired results in hours.

package org.arpit.java2blog;

import java.time.Duration;
import java.time.LocalDate;
import java.time.Month;

public class DifferenceBetweenTwoLocalDateHours {
    public static void main(String[] args) {
        LocalDate beforeDate = LocalDate.of(2022, Month.AUGUST, 23);
        LocalDate afterDate = LocalDate.of(2022, Month.DECEMBER, 25);

        long noOfHours = Duration.between(beforeDate.atStartOfDay(), afterDate.atStartOfDay()).toHours();
        System.out.println("Hours: "+noOfHours);
    }
}

Output

Hours: 2976

How to find difference between two LocalDate in Java in Minutes?

You can use Duration‘s between method to get difference between two LocalDate in Java. You need to call LocalDate‘s atStartOfDay() method to convert LocalDate to LocalDateTime and use it Duration‘s between() method. Call toMinutes() to get desired results in minutes.

package org.arpit.java2blog;

import java.time.Duration;
import java.time.LocalDate;
import java.time.Month;

public class DifferenceBetweenTwoLocalDateDays {
    public static void main(String[] args) {
        LocalDate beforeDate = LocalDate.of(2022, Month.AUGUST, 23);
        LocalDate afterDate = LocalDate.of(2022, Month.DECEMBER, 25);

        long noOfMinutes = Duration.between(beforeDate.atStartOfDay(), afterDate.atStartOfDay()).toMinutes();
        System.out.println("Minutes: "+noOfMinutes);
    }
}

Output

Minutes: 178560

How to find difference between two LocalDate in Java in seconds?

You can use Duration‘s between method to get difference between two LocalDate in Java. You need to call LocalDate‘s atStartOfDay() method to convert LocalDate to LocalDateTime and use it Duration‘s between() method. Call toMinutes() to get desired results in minutes.

package org.arpit.java2blog;

import java.time.Duration;
import java.time.LocalDate;
import java.time.Month;

public class DifferenceBetweenTwoLocalDateDays {
    public static void main(String[] args) {
        LocalDate beforeDate = LocalDate.of(2022, Month.AUGUST, 23);
        LocalDate afterDate = LocalDate.of(2022, Month.DECEMBER, 25);

        long noofSeconds = Duration.between(beforeDate.atStartOfDay(), afterDate.atStartOfDay()).toSeconds();
        System.out.println("Seconds: "+noofSeconds);
    }
}

Output

Seconds: 10713600

That’s all about how to find difference two LocalDate in Java.

]]>
https://java2blog.com/find-difference-between-two-localdate-java/feed/ 0
Get List of Weekday Names in Java https://java2blog.com/get-list-of-weekday-names-java/?utm_source=rss&utm_medium=rss&utm_campaign=get-list-of-weekday-names-java https://java2blog.com/get-list-of-weekday-names-java/#respond Mon, 26 Sep 2022 18:17:37 +0000 https://java2blog.com/?p=20758 In this post, we will see how to get list of weekday names in Java.

Using DateFormatSymbols’s getWeekdays() method

We can use DateFormatSymbols's getWeekdays() to get list of weekday names in Java. It will provide complete weekday names like Sunday, Monday etc.

package org.arpit.java2blog;

import java.text.DateFormatSymbols;
import java.util.Arrays;

public class GetListOfWeekdayNames {

    public static void main(String[] args) {

        // Create DateFormatSymbols with default Locale
        DateFormatSymbols dfs = new DateFormatSymbols();

        String[] weekdays = dfs.getWeekdays();
        System.out.println("Weekdays are: "+ Arrays.toString(weekdays));
    }
}

Output

Weekdays are: [, Sunday, Monday, Tuesday, Wednesday, Thursday, Friday, Saturday]

Using DateFormatSymbols’s getShortWeekdays() method [For short names]

If you need short names rather than complete weekdays name, you can use DateFormatSymbols's getShortWeekdays().

package org.arpit.java2blog;

import java.text.DateFormatSymbols;
import java.util.Arrays;
import java.util.Locale;

public class GetListOfWeekdayNames {

    public static void main(String[] args) {

        // Create DateFormatSymbols with default Locale
        DateFormatSymbols dfs = new DateFormatSymbols();

        String[] shortWeekDays = dfs.getShortWeekdays();
        System.out.println("Weekdays with short names are: "+ Arrays.toString(shortWeekDays));
    }
}

Output

Weekdays with short names are: [, Sun, Mon, Tue, Wed, Thu, Fri, Sat]

Using DateFormatSymbols’s getWeekdays() with Locale

If you are looking for weekday names in different Locale like German or French, you can specify Locale while creating object of DateFormatSymbols. It will work for both methods i.e. getWeekdays() and getShortWeekdays().

package org.arpit.java2blog;

import java.text.DateFormatSymbols;
import java.util.Arrays;
import java.util.Locale;

public class GetListOfWeekdayNames {

    public static void main(String[] args) {

        DateFormatSymbols dfs = new DateFormatSymbols(Locale.GERMAN);

        String[] weekdays = dfs.getWeekdays();
        System.out.println("German weekdays are: "+ Arrays.toString(weekdays));

        String[] shortWeekDays = dfs.getShortWeekdays();
        System.out.println("German weekdays in short name are: "+ Arrays.toString(shortWeekDays));
    }
}

Output

German weekdays are: [, Sonntag, Montag, Dienstag, Mittwoch, Donnerstag, Freitag, Samstag]
German weekdays in short name are: [, So., Mo., Di., Mi., Do., Fr., Sa.]

That’s all about how to get list of months in Java.

]]>
https://java2blog.com/get-list-of-weekday-names-java/feed/ 0
Get List of Month Names in Java https://java2blog.com/get-list-of-month-names-java/?utm_source=rss&utm_medium=rss&utm_campaign=get-list-of-month-names-java https://java2blog.com/get-list-of-month-names-java/#respond Sat, 24 Sep 2022 10:40:00 +0000 https://java2blog.com/?p=20743 In this post, we will see how to get list of months name in Java.

Using DateFormatSymbols’s getMonth() method

We can use DateFormatSymbols's getMonth() to get list of months in Java. It will provide complete month names like January, February etc.

package org.arpit.java2blog;

import java.text.DateFormatSymbols;
import java.util.Arrays;

public class GetListOfMonths {

    public static void main(String[] args) {

        // Create DateFormatSymbols with default Locale
        DateFormatSymbols dfs = new DateFormatSymbols();

        String[] monthNames = dfs.getMonths();
        System.out.println("Months are: "+ Arrays.toString(monthNames));
    }
}

Output

Months are: [January, February, March, April, May, June, July, August, September, October, November, December, ]

Using DateFormatSymbols’s getShortMonths() method [ For short names]

If you need short names rather than complete months name, you can use DateFormatSymbols's getShortMonths().

package org.arpit.java2blog;

import java.text.DateFormatSymbols;
import java.util.Arrays;

public class GetListOfMonths {

    public static void main(String[] args) {

        // Create DateFormatSymbols with default Locale
        DateFormatSymbols dfs = new DateFormatSymbols();

        String[] shortMonthNames = dfs.getShortMonths();
        System.out.println("Months with short names are: "+ Arrays.toString(shortMonthNames));
    }
}

Output

Months with short names are: [Jan, Feb, Mar, Apr, May, Jun, Jul, Aug, Sep, Oct, Nov, Dec, ]

Using DateFormatSymbols’s getMonth() with Locale

If you are looking for month names in different Locale like German or French, you can specify Locale while creating object of DateFormatSymbols. It will work for both methods i.e. getMonth() and getShortMonths().

package org.arpit.java2blog;

import java.text.DateFormatSymbols;
import java.util.Arrays;
import java.util.Locale;

public class GetListOfMonths {

    public static void main(String[] args) {

        // Create DateFormatSymbols with default Locale
        DateFormatSymbols dfs = new DateFormatSymbols(Locale.GERMAN);

        String[] monthNames = dfs.getMonths();
        System.out.println("German Months are: "+ Arrays.toString(monthNames));

        String[] shortMonthNames = dfs.getShortMonths();
        System.out.println("German Months in short name are: "+ Arrays.toString(shortMonthNames));
    }
}

Output

German Months are: [Januar, Februar, März, April, Mai, Juni, Juli, August, September, Oktober, November, Dezember, ]
German Months in short name are: [Jan., Feb., März, Apr., Mai, Juni, Juli, Aug., Sep., Okt., Nov., Dez., ]

That’s all about how to get list of months in Java.

]]>
https://java2blog.com/get-list-of-month-names-java/feed/ 0
Get Unix Timestamp in Java https://java2blog.com/get-unix-timestamp-java/?utm_source=rss&utm_medium=rss&utm_campaign=get-unix-timestamp-java https://java2blog.com/get-unix-timestamp-java/#respond Tue, 20 Sep 2022 08:17:38 +0000 https://java2blog.com/?p=20654 In this post, we will get unix timestamp in Java.

As per wikipedia
Unix time is a system for describing a point in time. It is the number of seconds that have elapsed since the Unix epoch, excluding leap seconds. The Unix epoch is 00:00:00 UTC on 1 January 1970.

Unix time is standard way to describe point in time and used at multiple unix like operating system.

Ways to get unix timestamp in Java

There are multiple ways to get unix timestamp in Java.

Using Instant class

You can use Instant class to get unix timestamp in java in case you are using Java 8 or higher.

package org.arpit.java2blog;

import java.time.Instant;

public class GetUnixTimeStampMain {

    public static void main(String[] args) {
        long unixTimestamp = Instant.now().getEpochSecond();
        System.out.println("Unix timestamp: "+unixTimestamp);
    }
}

Output

Unix timestamp: 1663659792

Using System.currentTimeMillis()

You can avoid date/Instant object creation and use System.currentTimeMillis() to get current time in millisecond. You can convert milliseconds to seconds by diving it by 1000L.

package org.arpit.java2blog;

public class GetUnixTimeStampSystem {

    public static void main(String[] args) {
        long unixTimestamp = System.currentTimeMillis()/1000L;
        System.out.println("Unix timestamp: " + unixTimestamp);
    }
}

Output

Unix timestamp: 1663660088

Using Date’s getTime() method

You can use legacy Date’s getTime() method to get unix timestamp in Java. You need to divide() time by 1000L to convert milliseconds to seconds.

package org.arpit.java2blog;

import java.util.Date;

public class GetUnixTimeStampDate {

    public static void main(String[] args) {
        long unixTimestamp = new Date().getTime()/1000L;
        System.out.println("Unix timestamp: " + unixTimestamp);
    }
}

Output

Unix timestamp: 1663660228

Convert Date to unix timestamp in Java

Using Instant class

You can get Instant() from Date object using toInstant() method and get unix timestamp using getEpochSecond().

package org.arpit.java2blog;

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

public class GetUnixTimeStampDate {

    public static void main(String[] args) {
        Calendar cal = Calendar.getInstance();
        cal.set(Calendar.DAY_OF_MONTH, 20);
        cal.set(Calendar.MONTH, 8);
        cal.set(Calendar.YEAR, 2022);

        Date givenDate = cal.getTime();
        long unixTimestamp = givenDate.toInstant().getEpochSecond();
        System.out.println("Unix timestamp: "+unixTimestamp);

    }
}

Output

Unix timestamp: 1663660884

You can also use LocalDate instead of java.util.Date. You need to first convert LocalDate to Instant and use getEpochSecond() to convert LocalDate to unix timestamp in Java.

package org.arpit.java2blog;

import java.time.Instant;
import java.time.LocalDate;
import java.time.ZoneOffset;

public class GetUnixTimeStampDate {

    public static void main(String[] args) {
        // Get LocalDate object
        LocalDate localDate = LocalDate.of(2022,10,23);

        // Convert LocalDate to Instant with ZoneOffSet
        Instant instant = localDate.atStartOfDay().toInstant(ZoneOffset.UTC);

        // Get unix timestamp from Instant
        long epochSecond = instant.getEpochSecond();
        System.out.println("Unix timestamp: "+epochSecond);

    }
}

Output

Unix timestamp: 1666483200

Using Date’s getTime() method

You can use legacy Date’s getTime() method to convert Date to unixTimeStamp in Java. You need to divide() time by 1000L to convert milliseconds to seconds.

package org.arpit.java2blog;

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

public class GetUnixTimeStampDate {

    public static void main(String[] args) {
        Calendar cal = Calendar.getInstance();
        cal.set(Calendar.DAY_OF_MONTH, 20);
        cal.set(Calendar.MONTH, 8);
        cal.set(Calendar.YEAR, 2022);

        Date givenDate = cal.getTime();
        long unixTimestamp = givenDate.getTime()/1000L;
        System.out.println("Unix timestamp: "+unixTimestamp);

    }
}

Output

Unix timestamp: 1663660228

That’s all about how to get Get Unix Timestamp in Java.

]]>
https://java2blog.com/get-unix-timestamp-java/feed/ 0
Check if Date Is Weekend or Weekday in Java https://java2blog.com/check-if-date-is-weekend-or-weekday-java/?utm_source=rss&utm_medium=rss&utm_campaign=check-if-date-is-weekend-or-weekday-java https://java2blog.com/check-if-date-is-weekend-or-weekday-java/#respond Fri, 16 Sep 2022 18:51:13 +0000 https://java2blog.com/?p=20550 In this post, we will see how to check if Date is weekend or weekday in Java.

Please note that we will consider Saturaday/Sunday as weekend and rest five days of week as weekdays.

Using LocalDate’s getDayOfWeek() method

We can use LocalDate’s getDayOfWeek() method to check if given date is weekend or weekday in Java. This method returns day from Sunday to Monday and we can use String comparison to check where day is weekend or not.

Here is java program:

package org.arpit.java2blog;

import java.time.LocalDate;

public class CheckWeekendMain {

    public static void main(String[] args) {
        LocalDate ld1=LocalDate.of(2022,9,17);
        boolean isWeekend1 = isWeekEnd(ld1);
        System.out.println("17 Sep 2022 isWeekend: "+isWeekend1);

        LocalDate ld2=LocalDate.of(2022,9,19);
        boolean isWeekend2 = isWeekEnd(ld2);
        System.out.println("19 Sep 2022 isWeekend: "+isWeekend2);
    }

      /*Function to check if given date is weekend or not*/
    public static boolean isWeekEnd(LocalDate localDate)
    {
        String dayOfWeek = localDate.getDayOfWeek().toString();
        if("SATURDAY".equalsIgnoreCase(dayOfWeek)||
        "SUNDAY".equalsIgnoreCase(dayOfWeek))
        {
            return true;
        }
        return false;
    }
}

Output

17 Sep 2022 isWeekend: true
19 Sep 2022 isWeekend: false

Using LocalDate with DayOfWeek

LocalDate’s get(ChronoField.DAY_OF_WEEK) method returns integer ranging from 1 to 7. We can get DayOfWeek from the integer using DayOfWeek's of() method and compare it with DayOfWeek.SUNDAY and DayOfWeek.SATURDAY to determine if date is weekend or weekday in Java.

1 represents Monday and 7 represents Sunday.

package org.arpit.java2blog;

import java.time.DayOfWeek;
import java.time.LocalDate;
import java.time.temporal.ChronoField;

public class CheckWeekendMain {

    public static void main(String[] args) {
        LocalDate ld1=LocalDate.of(2022,9,17);
        boolean isWeekend1 = isWeekEnd(ld1);
        System.out.println("17 Sep 2022 isWeekend: "+isWeekend1);

        LocalDate ld2=LocalDate.of(2022,9,19);
        boolean isWeekend2 = isWeekEnd(ld2);
        System.out.println("19 Sep 2022 isWeekend: "+isWeekend2);
    }

    /*Function to check if given date is weekend or not*/
    public static boolean isWeekEnd(LocalDate localDate)
    {
        DayOfWeek dayOfWeek = DayOfWeek.of(localDate.get(ChronoField.DAY_OF_WEEK));
        if(DayOfWeek.SUNDAY == dayOfWeek|| DayOfWeek.SATURDAY == dayOfWeek)
        {
            return true;
        }
        return false;
    }
}

Output

17 Sep 2022 isWeekend: true
19 Sep 2022 isWeekend: false

Using Date and Calendar classes

We can convert Date to Calenday object and use Calendar.get(Calendar.DAY_OF_WEEK) to get integer which represents day of the week and compare it with Calendar.SATURDAY or Calendar.SUNDAY to check if given date is weekend or weekday.

In case of Calendar, 1 represents Sunday and 7 represents Saturday.

package org.arpit.java2blog;

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

public class CheckWeekEndCalendarMain {

    public static void main(String[] args) {
        Date d1=new Date(2022,8,17);
        boolean isWeekend1 = isWeekEnd(d1);
        System.out.println("17 Sep 2022 isWeekend: "+isWeekend1);

        Date d2=new Date(2022,8,19);
        boolean isWeekend2 = isWeekEnd(d2);
        System.out.println("19 Sep 2022 isWeekend: "+isWeekend2);
    }

    /* Function to check if given date is weekend or not */
    public static boolean isWeekEnd(final Date date)
    {
        Calendar cal = Calendar.getInstance();
        cal.setTime(date);

        int day = cal.get(Calendar.DAY_OF_WEEK);
        return day == Calendar.SUNDAY || day == Calendar.SATURDAY;
    }
}

Output

17 Sep 2022 isWeekend: true
19 Sep 2022 isWeekend: false

That’s all about how to check if date is weekend or weekday in Java.

]]>
https://java2blog.com/check-if-date-is-weekend-or-weekday-java/feed/ 0
Format Date to yyyy-MM-dd in java https://java2blog.com/format-date-to-yyyy-mm-dd-java/?utm_source=rss&utm_medium=rss&utm_campaign=format-date-to-yyyy-mm-dd-java https://java2blog.com/format-date-to-yyyy-mm-dd-java/#respond Wed, 25 May 2022 06:40:38 +0000 https://java2blog.com/?p=19203 In this post, we will see how to Format Date to yyyy-MM-dd in java.

There are multiple ways to format Date to yyyy-MM-dd in java. Let’s go through them.

Using DateTimeFormatter with LocalDate (Java 8)

To Format Date to yyyy-MM-dd in java:

  • Create a LocalDateTime object.
  • Use DateTimeFormatter.ofPattern() to specify the pattern yyyy-MM-dd
  • Call format() method on DateTimeFormatter and pass LocalDateTime object
  • Get result in String with date format yyyy-mm-dd.

Let’s see with the help of example:

package org.arpit.java2blog;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Locale;

public class FormatLocalDate {

    public static void main(String[] args) {
        LocalDateTime ldt = LocalDateTime.now();
        String formattedDateStr = DateTimeFormatter.ofPattern("yyyy-MM-dd", Locale.ENGLISH)
                                  .format(ldt);
        System.out.println("Formatted Date in String format: "+formattedDateStr);
    }
}

Output:

Formatted Date in String format: 2022-05-25

Using SimpleDateFormat

To Format Date to yyyy-MM-dd in java:

  • Create Date object
  • Create SimpleDateFormat with pattern yyyy-MM-dd
  • Call format() method on SimpleDateFormat and pass Date object
  • Get result in String with date format yyyy-mm-dd.
package org.arpit.java2blog;

import java.text.SimpleDateFormat;
import java.util.Date;

public class FormatUsingSimpleDateFormat {

    public static void main(String[] args) {
        Date date = new Date();
        System.out.println("Original Date: "+date);

        // Specify format as "yyyy-MM-dd"
        SimpleDateFormat dmyFormat = new SimpleDateFormat("yyyy-MM-dd");

        // Use format method on SimpleDateFormat
        String formattedDateStr = dmyFormat.format(date);
        System.out.println("Formatted Date in String format: "+formattedDateStr);
    }
}

Output:

Original Date: Wed May 25 11:41:27 IST 2022
Formatted Date in String format: 2022-05-25

Using Calendar class

To Format Date to yyyy-MM-dd in java:

  • Use Calendar's setTime() method to set current date
  • Use calendar class to get day, month and year using Calendar.get() methods.
  • Create format yyyy-MM-dd using String concatenation.

This is not a recommended approach as it does not specify format explicitly and is more error prone.

Let’s see with the help of example:

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

public class FormatWithCalendar {

    public static void main(String[] args) {
        Date date = new Date();
        Calendar calendar = new GregorianCalendar();
        calendar.setTime(date);
        int day   = calendar.get(Calendar.DAY_OF_MONTH);
        int month = calendar.get(Calendar.MONTH) + 1; // {0 - 11}
        int year  = calendar    .get(Calendar.YEAR);

        String yyyymmddFormat = (year)+"-"+((month<10)?"0"+month:month) + "-" + ((day<10)?"0"+day:day);
        System.out.println("Formatted Date in yyyy-MM-dd format: " + yyyymmddFormat);
    }
}

Output:

Formatted Date in yyyy-MM-dd format: 2022-05-25

Note that we have added 1 after getting month using calendar.get(Calendar.MONTH) because it returns month from 0 to 11. 0 denotes January and 11 denotes December.

That’s all about how to Format Date to yyyy-MM-dd in java.

]]>
https://java2blog.com/format-date-to-yyyy-mm-dd-java/feed/ 0
Get number of days in Month in java https://java2blog.com/get-number-of-days-month-java/?utm_source=rss&utm_medium=rss&utm_campaign=get-number-of-days-month-java https://java2blog.com/get-number-of-days-month-java/#respond Sun, 06 Feb 2022 18:42:32 +0000 https://java2blog.com/?p=19206 Learn about how to get number of days in Month in java.

Get number of days in Month in java

Using YearMonth’s lengthOfMonth() [Java 8]

You can use YearMonth‘s lengthOfMonth() method to get number of days in Month in java.

  • Pass Year and month to YearMonth’s of and create YearMonth object.
  • Call lengthOfMonth() on YearMonth’s object to get number of days in Month in java.
package org.arpit.java2blog;

import java.time.YearMonth;

public class GetNumberOfDaysInMonthJava {

    public static void main(String[] args) {
        // Get number of days in given month of the year
        int numberOfDaysInMonth1 = getNumberOfDaysInMonth(2019, 2);
        System.out.println("Number of days in Feb 2019: "+numberOfDaysInMonth1);

        int numberOfDaysInMonth2 = getNumberOfDaysInMonth(2020, 2);
        System.out.println("Number of days in Feb 2020: "+numberOfDaysInMonth2);

    }

    // Method to get number of days in month
    public static int getNumberOfDaysInMonth(int year,int month)
    {
        YearMonth yearMonthObject = YearMonth.of(year, month);
        int daysInMonth = yearMonthObject.lengthOfMonth();
        return daysInMonth;
    }
}

Output:

Number of days in Feb 2019: 28
Number of days in Feb 2020: 29

Using LocalDate’s lengthOfMonth [Java 8]

You can use LocalDate‘s lengthOfMonth() method to get number of days in Month in java.

  • Pass Year and month to LocalDate’s of and create YearMonth object.
  • Call lengthOfMonth() on LocalDate’s object to get number of days in Month in java.
package org.arpit.java2blog;

import java.time.LocalDate;

public class GetNumberOfDaysInMonthLocalDateJava {

    public static void main(String[] args) {

        // Get number of days in given month of the year
        int numberOfDaysInMonth1 = getNumberOfDaysInMonth(2019, 2);
        System.out.println("Number of days in Feb 2019: "+numberOfDaysInMonth1);

        int numberOfDaysInMonth2 = getNumberOfDaysInMonth(2020, 2);
        System.out.println("Number of days in Feb 2020: "+numberOfDaysInMonth2);
    }

    // Method to get number of days in month
    public static int getNumberOfDaysInMonth(int year,int month)
    {
        // LocalDate object
        LocalDate date = LocalDate.of(year, month, 1);
        return date.lengthOfMonth();
    }
}

Output:

Number of days in Feb 2019: 28
Number of days in Feb 2020: 29

Using Calendar

You can use Calendar’s getActualMaximum() to get number of days in Month in java.

  • Create instance of Calendar object.
  • Call Calendar’s getActualMaximum() to get number of days in Month in java.
package org.arpit.java2blog;

import java.util.Calendar;
import java.util.GregorianCalendar;

public class GetNumberOfDaysInMonthCalendarJava {

    public static void main(String[] args) {

        // Get number of days in given month of the year
        int numberOfDaysInMonth1 = getNumberOfDaysInMonth(2019, Calendar.FEBRUARY);
        System.out.println("Number of days in Feb 2019: "+numberOfDaysInMonth1);

        int numberOfDaysInMonth2 = getNumberOfDaysInMonth(2020, Calendar.FEBRUARY);
        System.out.println("Number of days in Feb 2020: "+numberOfDaysInMonth2);
    }

    // Method to get number of days in month
    public static int getNumberOfDaysInMonth(int year,int month)
    {
        // Create a calendar object and set year and month
        Calendar mycal = new GregorianCalendar(year, month, 1);
        int daysInMonth = mycal.getActualMaximum(Calendar.DAY_OF_MONTH);
        return daysInMonth;
    }
}

Output:

Number of days in Feb 2019: 28
Number of days in Feb 2020: 29

That’s all about how to get number of days in Month in java

]]>
https://java2blog.com/get-number-of-days-month-java/feed/ 0