14

我正在尝试获取给定月份和年份的第一个日期和最后一个日期。我使用以下代码以 yyyyMMdd 格式获取最后日期。但无法获得这种格式。然后我想要相同格式的开始日期。我仍在努力。任何人都可以帮助我修复以下代码。

public static java.util.Date calculateMonthEndDate(int month, int year) {
    int[] daysInAMonth = { 29, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 };
    int day = daysInAMonth[month];
    boolean isLeapYear = new GregorianCalendar().isLeapYear(year);

    if (isLeapYear && month == 2) {
        day++;
    }
    GregorianCalendar gc = new GregorianCalendar(year, month - 1, day);
    java.util.Date monthEndDate = new java.util.Date(gc.getTime().getTime());
    return monthEndDate;
}

public static void main(String[] args) {
    int month = 3;
    int year = 2076;
    final java.util.Date calculatedDate = calculateMonthEndDate(month, year);
    SimpleDateFormat format = new SimpleDateFormat("yyyyMMdd");
    format.format(calculatedDate);
    System.out.println("Calculated month end date : " + calculatedDate);
} 
4

9 回答 9

21
于 2015-09-01T02:23:29.187 回答
8

只需您可以使用日历类。你应该分配你想要的月份变量

        Calendar gc = new GregorianCalendar();
        gc.set(Calendar.MONTH, month);
        gc.set(Calendar.DAY_OF_MONTH, 1);
        Date monthStart = gc.getTime();
        gc.add(Calendar.MONTH, 1);
        gc.add(Calendar.DAY_OF_MONTH, -1);
        Date monthEnd = gc.getTime();
        SimpleDateFormat format = new SimpleDateFormat("yyyyMMdd");

        System.out.println("Calculated month start date : " + format.format(monthStart));
        System.out.println("Calculated month end date : " + format.format(monthEnd));
于 2015-04-17T12:25:12.330 回答
7

第一天:

Calendar.getInstance().getActualMinimum(Calendar.DAY_OF_MONTH);

一个月的最后一天:

Calendar.getInstance().getActualMaximum(Calendar.DAY_OF_MONTH);
于 2017-01-04T16:05:24.363 回答
5
SimpleDateFormat format = new SimpleDateFormat("yyyyMMdd");
format.format(calculatedDate);
System.out.println("Calculated month end date : " + calculatedDate);

将其更改为

SimpleDateFormat format = new SimpleDateFormat("yyyyMMdd");
String formattedDate =  format.format(calculatedDate);
System.out.println("Calculated month end date : " + formattedDate);

了解更多详情

http://docs.oracle.com/javase/1.5.0/docs/api/java/text/DateFormat.html#format(java.util.Date)

另一种方法

package com.shashi.mpoole;

import java.text.SimpleDateFormat; 
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;

public class DateMagic {

     public static String PATTERN = "yyyyMMdd";

     static class Measure {
           private int month;
           private int year;
           private Calendar calendar;

           public Measure build() {

                calendar = Calendar.getInstance();
                calendar.set(year, month, 1);

                return this;
           }

           public Measure(int year, int month) {
                this.year(year);
                this.month(month);
           }

           public String min() {
                  return format(calendar.getActualMinimum(Calendar.DATE));
           }

           public String max() {
                  return format(calendar.getActualMaximum(Calendar.DATE));
           }

           private Date date(GregorianCalendar c) {
                  return new java.util.Date(c.getTime().getTime());

           }

           private GregorianCalendar gc(int day) {
                  return new GregorianCalendar(year, month, day);
           }

           private String format(int day) {

                  SimpleDateFormat format = new SimpleDateFormat(PATTERN);
                  return format.format(date(gc(day)));
           }

           public void month(int month) {
                  this.month = month - 1;
           }

           public void year(int year) {
                  this.year = year;
           }
      }

      public static void main(String[] args) {

             Measure measure = new Measure(2020, 6).build();

             System.out.println(measure.min());
             System.out.println(measure.max());

        
    }

}
于 2013-01-23T08:47:08.187 回答
5

获取开始日期

    GregorianCalendar gc = new GregorianCalendar(year, month-1, 1);
    java.util.Date monthEndDate = new java.util.Date(gc.getTime().getTime());
    System.out.println(monthEndDate);

:开始日期中的=1)

对于格式化的

SimpleDateFormat format = new SimpleDateFormat(/////////add your format here);
System.out.println("Calculated month end date : " + format.format(calculatedDate));
于 2013-01-23T09:02:21.977 回答
4

试试下面的代码一个月的最后一天: -

Calendar c = Calendar.getInstance();      
c.set(2012,3,1); //------>  
c.set(Calendar.DAY_OF_MONTH, c.getActualMaximum(Calendar.DAY_OF_MONTH));  

SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");  
System.out.println(sdf.format(c.getTime())); 

http://www.coderanch.com/t/385759/java/java/date-date-month

于 2013-12-13T05:31:45.173 回答
2

虽然,不完全是 OP 问题的答案,但以下方法会将当前月份的第一个和最后一个日期作为 Java 8+ LocalDate 实例给出。

public static LocalDate getCurrentMonthFirstDate() {
    return LocalDate.ofEpochDay(System.currentTimeMillis() / (24 * 60 * 60 * 1000) ).withDayOfMonth(1);
}

public static LocalDate getCurrentMonthLastDate() {
    return LocalDate.ofEpochDay(System.currentTimeMillis() / (24 * 60 * 60 * 1000) ).plusMonths(1).withDayOfMonth(1).minusDays(1);
}

旁注:使用LocalDate.ofEpochDay(...)代替可以LocalDate.now()大大提高性能。此外,使用millis-in-a-day 表达式而不是最终值,它86400000的性能更好。我最初认为后者会比表达式表现更好:P

为什么这个答案即使这不是 OP 问题的正确答案,我仍然在这里回答,因为当我搜索“java 8 get month start date”时谷歌显示了这个问题:)

于 2015-04-29T18:24:14.853 回答
1
        GregorianCalendar gc = new GregorianCalendar(year, selectedMonth-1, 1);
           java.util.Date monthStartDate = new java.util.Date(gc.getTime().getTime());
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(monthStartDate);
        calendar.add(calendar.MONTH, 1);
        calendar.add(calendar.DAY_OF_MONTH, -1);
           java.util.Date monthEndDate = new java.util.Date(calendar.getTime())
于 2014-09-01T06:23:21.960 回答
0
public static Date[] getMonthInterval(Date data) throws Exception {

    Date[] dates = new Date[2];

    Calendar start = Calendar.getInstance();
    Calendar end = Calendar.getInstance();

    start.setTime(data);
    start.set(Calendar.DAY_OF_MONTH, start.getActualMinimum(Calendar.DAY_OF_MONTH));
    start.set(Calendar.HOUR_OF_DAY, 0);
    start.set(Calendar.MINUTE, 0);
    start.set(Calendar.SECOND, 0);

    end.setTime(data);
    end.set(Calendar.DAY_OF_MONTH, end.getActualMaximum(Calendar.DAY_OF_MONTH));
    end.set(Calendar.HOUR_OF_DAY, 23);
    end.set(Calendar.MINUTE, 59);
    end.set(Calendar.SECOND, 59);

    //System.out.println("start "+ start.getTime());
    //System.out.println("end   "+ end.getTime());

    dates[0] = start.getTime();
    dates[1] = end.getTime();

    return dates;
}
于 2018-05-07T08:46:35.167 回答