Java date & time Format Explained [10+ Examples]


JAVA

Author: Bashir Alam
Reviewer: Deepak Prasad

Related Searches: java date, java date format, java localdate, java localtime, java current date, java time format, java get date, java datetime format

 

Introduction to Java date and time

In a programming language, sometimes we might need the current time or date. Java provides the Date class available in java.util package, this class encapsulates the current date and time. In this tutorial, we will learn about java date and time packages. We will learn how we can get the current time and date using a java programming language. We will also cover different methods and formats to display time and date by taking various examples. Moreover, we will also discuss the difference between duration and a period and will take examples of each.

All in all, this tutorial contains different operations that we can perform on java date and time and will help you to get started with java date and time.

 

Getting started with Java date and time

Our computer uses its system clock to apply a date and time stamp to every file you create and edit, including the documents we save from our applications and the email messages we send or receive. Time and date are crucial parts of computer performance.  In this section, we will discuss how we can get the current time and date using the java programming language.

 

Example-1 Display the current time (localTime) in Java

Now let us see how we can find the current time in the java programming language. We will use localTime class to get the current time. See the example below:

// importing local time
import java.time.LocalTime;
// Java main class
public class Main {
// main method
  public static void main(String[] args) {
    // java current time 
    LocalTime localTime = LocalTime.now();
    // printing the current time
    System.out.println(localTime); 
  }
}

Output:

11 : 17 : 17.775071

Notice that it displays the current time in hours: minutes: seconds format. If you will run the same code on your system, you will get a different output depending on the current time on your local system.

 

Example-2 Display the current date (localDate) in Java

Now let us see how we can display the current date in java. This time we have to import localDate class and use it to find the current date. See the example below:

// importing local time
import java.time.LocalDate;
// Java main class
public class Main {
// main method
  public static void main(String[] args) {
    // java date now 
    LocalDate Date = LocalDate.now();
    // printing the current date
    System.out.println(Date); 
  }
}

Output:

2021-09-11

Notice that it displays the java date in year - month - date format. You will get a different date depending on the date you will run this code on your system.

 

Example-3 Display local date and time (localDateTime)

Now let us display the date and time at the same time using localDateTime class. See the example below which displays the date and time at the same time.

// importing local Date time
import java.time.LocalDateTime;
// Java main class
public class Main {
  // main method
  public static void main(String[] args) {
    // java date and java time now
    LocalDateTime DateTime = LocalDateTime.now();
    // printing the current date and time
    System.out.println(DateTime); 
  }
}

Output:

2021 - 09 - 11 T 11 : 32 : 38.536186

Notice that we successfully displayed the current date and time using a java programming language. The symbol "T" in the output represents the time.

 

Example-4 Display Java date and time with default time zone

We already learned how we can display the java date and time. Now let us see how we can get the time along with the default time zone. See the example below:

// importing local Date time and time zone
import java.time.ZonedDateTime;
// Java main class
public class Main {
  // main method
  public static void main(String[] args) {
    // java data time with time zone
    ZonedDateTime now = ZonedDateTime.now();
    // printing the java date time and time zone
    System.out.println(now);                 
    System.out.println(now.getOffset());  
  }
}

Output:

2021 - 09 - 11 T 11 : 38 : 42.034139 + 06 : 00 [Asia/Bishkek]
+06:00

Notice that currently, I am in Kyrgyzstan that is why my default time zone is Asia/Bishkek. Your time zone might differ depending on your location.

 

Example-5 Display Java date time with specified time zone

Now let us see how we can print the java date time and time zone of the specified region. See the example below which print the time zone of Japan.

// Importing the zoneID
import java.time.ZoneId;
// importing local Date time and time zone
import java.time.ZonedDateTime;
// Java main class
public class Main {
  // main method
  public static void main(String[] args) {
    // java date time and time zone
    ZonedDateTime now = ZonedDateTime.now();
    // japan time zone
    ZonedDateTime japan = now.withZoneSameInstant(ZoneId.of("Asia/Tokyo"));
    // pringint the time along with time zone
    System.out.println(japan);        
    System.out.println(japan.getOffset());  
  }
}

Output:

2021 - 09 - 11 T 14 : 47 : 27.078685 + 09 : 00 [Asia/Tokyo]
+09:00

Notice that we successfully print the time and time zone of Japan. You find the time zone of other regions as well using the above java program.

 

Formatting the Java date and time

In the above examples, you might have seen that the formatting was a little bit weird. For example, the seconds were in decimal points which is unusual for the time. In this section, we will format out displayed time in different formats.

 

Example-1 Formatting Java data and time

Let us first use simple formatting. We will remove the decimal points from the seconds. See the example below:

// importing local data time
import java.time.LocalDateTime;
// importing data time formatter
import java.time.format.DateTimeFormatter;
// java main class
public class Main {
    // java main method
    public static void main(String[] args) {
        //Get current java date time
        LocalDateTime nowdatetime = LocalDateTime.now();
        // printing java date time before formatting
        System.out.println("Before : " + nowdatetime);
        // providing formatting for java date time
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd  HH-mm-ss");
        // Formatting
        String formatDateTime = nowdatetime.format(formatter);
        // display formatted java date and time
        System.out.println("After : " + formatDateTime);
    }
}

Output:

Before : 2021 - 09 - 11 T 12 : 05 : 20.827818
After : 2021 - 09 - 11 12 - 05 - 20

Notice that now it looks better than the previous one.

 

Example-2 Formatting Java date and time

Now let us format our data and time in a different way. This time instead of using this "-" symbol, we will use the colon ":" symbol to separate the date and time. See the example belew:

// importing local data time
import java.time.LocalDateTime;
// importing data time formatter
import java.time.format.DateTimeFormatter;
// java main class
public class Main {
    // java main method
    public static void main(String[] args) {
        //Get current java date time
        LocalDateTime nowdatetime = LocalDateTime.now();
        // printing java date time before formatting
        System.out.println("Before : " + nowdatetime);
        // providing formatting for java date time
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy:MM:dd :: HH:mm:ss");
        // Formatting
        String formatDateTime = nowdatetime.format(formatter);
        // display formatted java date and time
        System.out.println("After : " + formatDateTime);
    }
}

Output:

Before : 2021-09-11T12:21:59.431708
After : 2021:09:11 :: 12:21:59

Notice that now it looks good. You can also format the java date and time in a different way using the above method.

 

Difference between period and duration

A duration object is measured in seconds or nanoseconds and does not use date-based constructs such as years, months, and days, though the class provides methods that convert to days, hours, and minutes. It can have a negative value if it is created with an endpoint that occurs before the start point. While the period class provides various get methods, such as getMonths, getDays, and getYears, so that we can extract the amount of time from the period. The total period of time is represented by all three units together: months, days, and years. In the following sections, we will take examples of each to make it more clear.

 

Example of Duration in Java programming language

We already had discussed that duration is measured in seconds or nanoseconds and does not use date-based constructs such as years, months, and days. Let us take a java program to print the duration time. See the example below which uses  java.time.Duration to find out the difference in seconds between two LocalDateTime:

// importing duration
import java.time.Duration;
// importing local data and time
import java.time.LocalDateTime;
// importing month
import java.time.Month;
// java main class
public class Main {
    // java main method
    public static void main(String[] args) {
        // Test Duration.between
        System.out.println("Duration between ! ");
        // using localdatetime to create a time
        LocalDateTime previousDate = LocalDateTime.of(2021, Month.AUGUST, 31, 2, 2, 50);
        LocalDateTime newDate = LocalDateTime.of(2021, Month.NOVEMBER, 19, 1, 1, 45);
        // printing out the created java date
        System.out.println(previousDate);
        System.out.println(newDate);
        //  finding the duration between the create java date
        Duration duration = Duration.between(previousDate, newDate);
        // printing the durations
        System.out.println(duration.getSeconds() + " seconds");

    }
}

Output:

Duration between !
2021 - 08 - 31 T 02 : 02 : 50
2021 - 11 - 19 T 01 : 01 : 45
6908335 seconds

Notice that we got the difference between the two dates in seconds.

 

Example of Period in Java programming language

As we already discussed that the total period of time is represented by all three units together: months, days, and years. Here let us take an example of a period using the java programming language. See the example below:

// Importing localDate
import java.time.LocalDate;
// Importing month
import java.time.Month;
// Java period
import java.time.Period;
// Java main class
public class Main {
   // java main method
    public static void main(String[] args) {
        System.out.println("Period between :");
        // creating java date
        LocalDate previousDate = LocalDate.of(2021, Month.AUGUST, 31);
        LocalDate newDate = LocalDate.of(2021, Month.NOVEMBER, 16);
        // printing the created java date
        System.out.println(previousDate);
        System.out.println(newDate);
        // check period between java dates
        Period period = Period.between(previousDate, newDate);
        // printing the result
        System.out.print(period.getYears() + " years,");
        System.out.print(period.getMonths() + " months,");
        System.out.print(period.getDays() + " days");
    }
}

Output:

Period between :
2021-08-31
2021-11-16
0 years,2 months,16 days

Notice that this time we get the difference between the given dates in Years: months: days format instead of seconds.

 

Summary

Date and time play an important role in any programming language because our computer uses its system clock to apply a date and time stamp to every file you create and edit, including the documents we save from our applications and the email messages we send or receive. In the Java programming language, we have a lot of different functionalities, classes, and methods to apply and find a date and the time. In this tutorial, we learned how we can find the local time and date using a java programming language.

We also learned to format the date and time in different ways using various examples. Moreover, we also differentiate between the java period and java duration by taking different examples. In a nutshell, this tutorial contains all the necessary information that you need in order to start working with java date, and time.

 

Further Reading

Java date and time
Java period and duration
More about java date

 

Bashir Alam

Bashir Alam

He is a Computer Science graduate from the University of Central Asia, currently employed as a full-time Machine Learning Engineer at uExel. His expertise lies in Python, Java, Machine Learning, OCR, text extraction, data preprocessing, and predictive models. You can connect with him on his LinkedIn profile.

Can't find what you're searching for? Let us assist you.

Enter your query below, and we'll provide instant results tailored to your needs.

If my articles on GoLinuxCloud has helped you, kindly consider buying me a coffee as a token of appreciation.

Buy GoLinuxCloud a Coffee

For any other feedbacks or questions you can send mail to admin@golinuxcloud.com

Thank You for your support!!

Leave a Comment