TODAY JAVA SCHOOL

In java school, programming, design, computer general knowledge, web application, software, web services, social media, digital marketing, oops, concept of programming language, oops feature, console media, graphics medium, first programming, c, c ++ , Java, PHP, SQL, MySQL, HTML, HTML_5, J_query, JavaScript, Bootstrap, Framework, images with logos, examples, shared and explained.

https://www.amazon.in/b?node=26373545031&linkCode=ll2&tag=1234567801cdb-21&linkId=3b9882431b00409b44141e0344b35a15&language=en_IN&ref_=as_li_ss_tl

Breaking

Thursday, 26 December 2019

date and time api in java 8 | date and time in java


   Date and Time in Java

 


Java does not have a built-in Date class, but we can import the java.time package to work with the date and time API. The package includes many date and time classes. For example:

Display Current Date

To display the current date, import the java.time.LocalDate class, and use its now() method.
import java.time.LocalDate; // import the LocalDate class

public class MyClass {
  public static void main(String[] args) {
    LocalDate myObj = LocalDate.now(); // Create a date object
    System.out.println(myObj); // Display the current date
  }
}

Output:

30-11-2019

Display Current Time

 

 
date and time in java | java time now
date&time in java

To display the current time (hour, minute, second, and milliseconds), import the java.time.LocalTime class, and use its now() method:

Example:

import java.time.LocalTime; // import the LocalTime class
 
public class MyClass {
  public static void main(String[] args) {
    LocalTime myObj = LocalTime.now();
    System.out.println(myObj);
  }
}

Output:

6:41

Formatting Date and Time

The "T" in the example above is used to separate the date from the time. You can use the DateTimeFormatter class wit0h the ofPattern() method in the same package to format or parse date-time objects. The following example will remove both the "T" and milliseconds from the date-time:

Example:

import java.time.LocalDateTime; // Import the LocalDateTime class
import java.time.format.DateTimeFormatter; // Import the DateTimeFormatter class
 
public class MyClass {
  public static void main(String[] args) {
    LocalDateTime myDateObj = LocalDateTime.now();
    System.out.println("Before formatting: " + myDateObj);
    DateTimeFormatter myFormatObj = DateTimeFormatter.ofPattern("dd-MM-yyyy HH:mm:ss");
 
    String formattedDate = myDateObj.format(myFormatObj);
    System.out.println("After formatting: " + formattedDate);
  }
}

Output:

Before formatting:30-11-2019 6:14:11
After formatting:30-11-0219 6:14


No comments:

Post a Comment