
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Get Date for All Days of the Current Week in Java
In this article, we will learn to get date for all the days of the current week using Java. We will use the java.time package to get the current date and calculate the dates for the rest of the week based on the current day.
Steps to get date for all the days of the current week
Following are the steps to get date for all the days of the current week ?
- First we will import the DayOfWeek and LocalDate from java.time and Arrays class from java.util.
- We will get the current date using LocalDate.now().
- Retrieve all the days of the week using DayOfWeek.values().
- For each day of the week, calculate the date corresponding to that day in the current week.
- Output the list of dates for the entire week.
Java program to get date for all the days of the current week
Below is the Java program to get date for all the days of the current week ?
import java.time.DayOfWeek; import java.time.LocalDate; import java.util.Arrays; import static java.util.stream.Collectors.toList; public class Demo { public static void main(String[] args) { LocalDate listDays = LocalDate.now(); System.out.println("All the dates for the days in the week =\n"+Arrays.asList(DayOfWeek.values()).stream().map(listDays::with).collect(toList())); } }
Output
All the dates for the days in the week = [2019-04-15, 2019-04-16, 2019-04-17, 2019-04-18, 2019-04-19, 2019-04-20, 2019-04-21]
Code Explanation
In the above program, we first import LocalDate and DayOfWeek from java.time package to work with dates. We then get the current date using LocalDate.now(). Using DayOfWeek.values(), we fetch all the days of the week (from Monday to Sunday). We map each day to the corresponding date of the current week using the listDays.with() method. Finally, the list of dates is printed out and this will ensure that all the dates for the current week are calculated and displayed in one output.