ADVERTISEMENT
ADVERTISEMENT

Java program to parse individual components of date from the current date

Learn how to parse individual components of date from the current date in Java?
Submitted by Nidhi, on April 01, 2022

Problem Solution:

Create an object of the Date class and convert it into a string in a specified format. Then we will parse the date using the LocalDate class and its methods.

Program/Source Code:

The source code to parse individual components of date from the current date is given below. The given program is compiled and executed successfully.

// Java program to parse individual components 
// of date from current date

import java.util.Date;
import java.time.Month;
import java.time.LocalDate;
import java.text.*;

class Main {
  public static void main(String args[]) {
    Date date = new Date();
    DateFormat dtFormat = new SimpleDateFormat("yyyy-MM-dd");

    final String strDate = dtFormat.format(date);
    LocalDate lDate = LocalDate.parse(strDate);

    int dd = lDate.getDayOfMonth();

    Month mon = lDate.getMonth();

    int yyyy = lDate.getYear();

    System.out.println("Day  : " + dd);
    System.out.println("Month: " + mon);
    System.out.println("Year : " + yyyy);
  }
}

Output:

Day  : 1
Month: APRIL
Year : 2022

Explanation:

In the above program, we created a class Main that contains a static method main(). The main() method is the entry point for the program, here we created an object of the Date class and converted it into a string in a specified format. Then we parsed the components of date using methods of LocalDate class and printed the result on the console screen.

Java Date and Time Programs »


ADVERTISEMENT
ADVERTISEMENT


Comments and Discussions!



ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT

Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© https://www.includehelp.com some rights reserved.