将月份名称转换为日期范围

时间:2015-04-29 10:59:52

标签: java date

我需要将Monthname + Year转换为有效的日期范围。它需要与闰年等合作。

实施例

getDateRange("Feb",2015)  

应找到范围2015-02-01 -- 2015-02-28

虽然

getDateRange("Feb",2016)  

应找到范围2016-02-01 -- 2016-02-29

5 个答案:

答案 0 :(得分:2)

在Java 8中,您可以使用TemporalAdjusters

来实现
LocalDate firstDate= date.with(TemporalAdjusters.firstDayOfMonth());

LocalDate lastDate= date.with(TemporalAdjusters.lastDayOfMonth());

如果您只有年月,则最好使用YearMonth。从YearMonth开始,您可以轻松获得该月的长度。

 YearMonth ym= YearMonth.of(2015, Month.FEBRUARY);
 int monthLen= ym.lengthOfMonth();

答案 1 :(得分:1)

Java 8使日期时间操作变得非常简单。 对于Java 7及更低版本,你可以逃避这样的事情;

void getDate(String month, int year) throws ParseException {
    Date start = null, end = null;

    //init month and year
    SimpleDateFormat sdf = new SimpleDateFormat("MMM");
    Date parse = sdf.parse(month);
    Calendar instance = Calendar.getInstance();
    instance.setTime(parse);
    instance.set(Calendar.YEAR, year);

    //start is default first day of month
    start = instance.getTime();


    //calculate end
    instance.add(Calendar.MONTH, 1);
    instance.add(Calendar.DAY_OF_MONTH, -1);
    end = instance.getTime();

    System.out.println(start + " " + end);
}

输出将是" 2月",2015:

Sun Feb 01 00:00:00 EET 2015 
Sat Feb 28 00:00:00 EET 2015

答案 2 :(得分:1)

使用默认Java工具的Java 7解决方案:

public static void getDateRange(String shortMonth, int year) throws ParseException {
    SimpleDateFormat format = new SimpleDateFormat("MMM yyyy", Locale.ENGLISH);

    // the parsed date will be the first day of the given month and year
    Date startDate = format.parse(shortMonth + " " + year);

    Calendar calendar = Calendar.getInstance();
    calendar.setTime(startDate);
    // set calendar to the last day of this given month
    calendar.set( Calendar.DATE, calendar.getActualMaximum(Calendar.DATE));
    // and get a Date object
    Date endDate = calendar.getTime();

    // do whatever you need to do with your dates, return them in a Pair or print out
    System.out.println(startDate);
    System.out.println(endDate);
}

答案 3 :(得分:0)

尝试(未经测试):

public List<LocalDate> getDateRange(YearMonth yearMonth){
  List<LocalDate> dateRange = new ArrayList<>();
  IntStream.of(yearMonth.lengthOfMonth()).foreach(day -> dateRange.add(yearMonth.at(day));
  return  dateRange 
}

答案 4 :(得分:0)

Java 8提供了Masud提到的新日期API。

但是,如果您不在Java 8环境下工作,那么lamma date是一个不错的选择。

// assuming you know the year and month already. Because every month starts from 1, there should be any problem to create 
Date fromDt = new Date(2014, 2, 1);  

// build a list containing each date from 2014-02-01 to 2014-02-28
List<Date> dates = Dates.from(fromDt).to(fromDt.lastDayOfMonth()).build();