-1

How can I get (java.util.Date) date list from specific year and month

Example : I have a year like as '2017' and month name like as 'February' I want to get date list of February or any other months.

such as

2017-02-01,
2017-02-02,
2017-02-03,
2017-02-04,
2017-02-05,
2017-02-06,
2017-02-07
....
2017-02-28.

Please help me sample code, Thanks

Youcef LAIDANI
  • 55,661
  • 15
  • 90
  • 140
Md. Nasir Uddin
  • 151
  • 1
  • 13

6 Answers6

2

java.time

The java.util Date-Time API and their formatting API, SimpleDateFormat are outdated and error-prone. It is recommended to stop using them completely and switch to the modern Date-Time API*.

Also, quoted below is a notice from the home page of Joda-Time:

Note that from Java SE 8 onwards, users are asked to migrate to java.time (JSR-310) - a core part of the JDK which replaces this project.

Solution using java.time, the modern Date-Time API:

List<LocalDate> getDateList(int year, String monthname) {
    int month = Month.valueOf(monthname.toUpperCase()).getValue();
    
    return IntStream
            .rangeClosed(1, YearMonth.of(year, month).lengthOfMonth())
            .mapToObj(i -> LocalDate.of(year, month, i))
            .collect(Collectors.toList());
}

Demo:

import java.time.LocalDate;
import java.time.Month;
import java.time.YearMonth;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.IntStream;

public class Main {
    public static void main(String[] args) {
        // Test
        getDateList(2017, "February").forEach(System.out::println);
        System.out.println("=*==*==*=*=");
        getDateList(2016, "February").forEach(System.out::println);
    }

    static List<LocalDate> getDateList(int year, String monthname) {
        int month = Month.valueOf(monthname.toUpperCase()).getValue();
        
        return IntStream
                .rangeClosed(1, YearMonth.of(year, month).lengthOfMonth())
                .mapToObj(i -> LocalDate.of(year, month, i))
                .collect(Collectors.toList());
    }
}

Output:

2017-02-01
2017-02-02
...
...
...
2017-02-27
2017-02-28
=*==*==*=*=
2016-02-01
2016-02-02
...
...
...
2016-02-28
2016-02-29

ONLINE DEMO

Learn more about the modern Date-Time API from Trail: Date Time.


* For any reason, if you have to stick to Java 6 or Java 7, you can use ThreeTen-Backport which backports most of the java.time functionality to Java 6 & 7. If you are working for an Android project and your Android API level is still not compliant with Java-8, check Java 8+ APIs available through desugaring and How to use ThreeTenABP in Android Project.

Arvind Kumar Avinash
  • 71,965
  • 6
  • 74
  • 110
1

java.time

Use the modern date-time classes, in the java.time package.

String input = "2017 February" ;

Parse as a YearMonth object. Define a formatting pattern to match your input.

    String input = "2017 February";
    DateTimeFormatter f = DateTimeFormatter.ofPattern ( "uuuu MMMM" , Locale.US );
    YearMonth ym = YearMonth.parse ( input , f );

Loop for the number of days in that month. For each day-of-month, get a LocalDate object.

System.out.println ( "===== Days of " + ym + " =====" );
for ( int i = 1 ; i <= ym.lengthOfMonth () ; i ++ ) {
    LocalDate localDate = ym.atDay ( i );
    System.out.println ( localDate );  // Uses standard ISO 8601 format by default when generating a string.
}
System.out.println ( "=================" );

===== Days of 2017-02 =====

2017-02-01

2017-02-02

2017-02-03 …

You can see that code run live at IdeOne.com.

If you want to see this kind of code written using Java Streams, see my Question: Use Java streams to collect objects generated in a for loop


About java.time

The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.

The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.

To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.

Where to obtain the java.time classes?

The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval, YearWeek, YearQuarter, and more.

Community
  • 1
  • 1
Basil Bourque
  • 303,325
  • 100
  • 852
  • 1,154
0

First, you need to find the number of days you can get for a specific month, this is easy with Calendar.getActualMaximum(int field)

Returns the maximum value that the specified calendar field could have, given the time value of this Calendar. For example, the actual maximum value of the MONTH field is 12 in some years, and 13 in other years in the Hebrew calendar system.

From this, just use a loop to create every value (or might be easier with Stream API, but I am not good with it...).

Here is a simple example of the usage of this method (not the answer at all):

Calendar c = Calendar.getInstance();
    for(int i = 0; i <= c.getActualMaximum(Calendar.MONTH); ++i){
        c.set(Calendar.MONTH, i);
        System.out.format("There is %d days in %d\n", c.getActualMaximum(Calendar.DAY_OF_MONTH), c.get(Calendar.MONTH));
    }

Output :

There is 31 days in 0
There is 28 days in 1
There is 31 days in 2
There is 30 days in 3
There is 31 days in 4
There is 30 days in 5
There is 31 days in 6
There is 31 days in 7
There is 30 days in 8
There is 31 days in 9
There is 30 days in 10
There is 31 days in 11
AxelH
  • 14,325
  • 2
  • 25
  • 55
0

You can use this :

  • First you should to get the first day from date from your input year and month 2017/February
  • Second you should to get the number of days of this month
  • Third you should to loop until the number to your days in your case from 1 to 28 and add a day to your date


public static void main(String[] args) throws ParseException {
    int year = 2017;
    String month = "February";
    SimpleDateFormat format = new SimpleDateFormat("yyyy/MMMM", Locale.US);
    Date utilDate = format.parse(year + "/" + month);
    //get first day of your month
    System.out.println(new SimpleDateFormat("yyyy/MM/dd").format(utilDate));

    //get days of months
    Calendar cal = Calendar.getInstance();
    cal.setTime(utilDate);
    int monthMaxDays = cal.getActualMaximum(Calendar.DAY_OF_MONTH);
    //loop and add a day to your date
    for (int i = 0; i < monthMaxDays - 1; i++) {
        cal.add(Calendar.DATE, 1);
        System.out.println(new SimpleDateFormat("yyyy/MM/dd").format(cal.getTime()));
    }
}

See this code run live at IdeOne.com.

Good luck

Basil Bourque
  • 303,325
  • 100
  • 852
  • 1,154
Youcef LAIDANI
  • 55,661
  • 15
  • 90
  • 140
  • Thank you so much. It's a great solution . – Md. Nasir Uddin Feb 16 '17 at 09:06
  • 1
    FYI, the troublesome old date-time classes such as [`java.util.Date`](https://docs.oracle.com/javase/8/docs/api/java/util/Date.html), [`java.util.Calendar`](https://docs.oracle.com/javase/8/docs/api/java/util/Date.html), and `java.text.SimpleTextFormat` are now [legacy](https://en.wikipedia.org/wiki/Legacy_system), supplanted by the [java.time](https://docs.oracle.com/javase/8/docs/api/java/time/package-summary.html) classes. – Basil Bourque Feb 16 '17 at 20:52
  • mmmm so what should i do @BasilBourque do you find my answer with no sense? – Youcef LAIDANI Feb 16 '17 at 20:56
  • 1
    No, not about being nonsensical. Your Answer’s code appears to be correct, and functional as we can see when [running it live at IdeOne.com](http://ideone.com/l1dXqr). I suggest recommending the use of the legacy date-time classes is poor advice given their many flaws, poor design, and confusing nature. We have the java.time classes, an *enormous* improvement, so use the modern alternative. Why drive a [Yugo](https://en.wikipedia.org/wiki/Zastava_Koral) when you have a [Honda](https://en.wikipedia.org/wiki/Honda_Civic) in the driveway? – Basil Bourque Feb 16 '17 at 21:18
0

As part of solution I created this high order property to get an array of dates from current month. This was for Android below API level 26.

val daysOfMonth: List<Date>
get() {
    val cal = Calendar.getInstance()
    val start = cal.getActualMinimum(Calendar.DAY_OF_MONTH)
    val ends = cal.getActualMaximum(Calendar.DAY_OF_MONTH)
    val days = mutableListOf<Date>()
    for (i in start..ends) {
        cal.set(Calendar.DAY_OF_MONTH, i)
        days.add(cal.time)
    }
    return days
}
Ole V.V.
  • 81,772
  • 15
  • 137
  • 161
Gustavo Ross
  • 399
  • 3
  • 7
  • The `Calendar` class is poorly designed and long outdated. Using it is not recommended. Use `LocalDate` and/or other classes from [java.time, the modern Java date and time API](https://docs.oracle.com/javase/tutorial/datetime/). – Ole V.V. Sep 01 '21 at 20:11
  • The problem is that LocalDate on Android is just supported after API 26, but I agree that Calendar is sad – Gustavo Ross Sep 03 '21 at 18:21
  • 1
    Well, the question was not about Android (and it seems you forgot to state that your answer was). I am no Android developer myself, but I read in many places that java.time and `LocalDate` are not limited to API level 26 and above. The solution for lower levels is [core library desugaring](https://developer.android.com/studio/write/java8-support-table). – Ole V.V. Sep 03 '21 at 18:59
  • definately, you are right! thanks a lot for sharing that – Gustavo Ross Oct 18 '21 at 19:44
-1

I have used JODA-data time to make my life easier and here is the solution:

package com.github.dibyaranjan.service;

import org.joda.time.DateTime;

public class Test {
    public static void main(String[] args) {
        DateTime dateTime = new DateTime();
        dateTime = dateTime.withDate(2017, 02, 01); // Used the date and time mentioned in your question
        int currentMonth = dateTime.getMonthOfYear();
        boolean isCurrentMonth = true;
        while (isCurrentMonth) {
            isCurrentMonth = (dateTime.getMonthOfYear() == currentMonth);
            if (isCurrentMonth) {
                String dateTimeFormatter = "yyyy-MM-dd";
                System.out.println(dateTime.toString(dateTimeFormatter));
            }
            dateTime = dateTime.plusDays(1);
        }
    }
}
NewUser
  • 3,729
  • 10
  • 57
  • 79
  • Is it really necessary to use Joda for this ? It seems it would be the same with Calendar or probably LocalDate (not sur for the last) – AxelH Feb 16 '17 at 07:45
  • @AxelH: Yeah, not a *must* but, I do have Joda in every project I work. So every solution related to dates come to my mind includes usage of Joda. – NewUser Feb 16 '17 at 08:29
  • @AxelH : And yeah. Code looks very clean and tidy as well, I don't want the next developer who sees my code to curse me :) – NewUser Feb 16 '17 at 08:30
  • I understand, that's part of your standard API package. No problem, the algorithm can be easily reproduce if someone doesn't want Joda. – AxelH Feb 16 '17 at 08:35