如何获取上个月的第一个日期和最后一个日期? (Java)

问题描述 投票:0回答:10

有了今天的日期,我应该得到上个月的第一个日期和最后一个日期。我无法想出任何逻辑。

例如,通过

05/30/2012
时,我应该得到
04/01/2012
04/30/2012

任何帮助将不胜感激。谢谢。

java datetime date
10个回答
36
投票

Calendar

Calendar cal = Calendar.getInstance();
cal.add(Calendar.MONTH, -1);
cal.set(Calendar.DATE, 1);
Date firstDateOfPreviousMonth = cal.getTime();

cal.set(Calendar.DATE, cal.getActualMaximum(Calendar.DATE)); // changed calendar to cal

Date lastDateOfPreviousMonth = cal.getTime();


10
投票

tl;博士

YearMonth.now().minusMonths( 1 ).atDay( 1 )

…还有…

YearMonth.now().minusMonths( 1 ).atEndOfMonth()

避免 j.u.Date

避免捆绑的

java.util.Date
.Calendar
类,因为它们非常麻烦。相反,请在 Java 8 及更高版本中使用 java.time 包

java.time

Java 8 中新的 java.time 框架教程)具有用于此目的的命令。

恰当命名的

YearMonth
类代表一年中的一个月,没有任何特定的日期或时间。从那里我们可以询问该月的第一天和最后一天。

ZoneId zoneId = ZoneId.of( "America/Montreal" );
YearMonth yearMonthNow = YearMonth.now( zoneId );
YearMonth yearMonthPrevious = yearMonthNow.minusMonths( 1 );
LocalDate firstOfMonth = yearMonthPrevious.atDay( 1 );
LocalDate lastOfMonth = yearMonthPrevious.atEndOfMonth();

乔达时间

更新: Joda-Time 项目现在处于 维护模式,团队建议迁移到 java.time 类。请参阅 Oracle 的教程

Joda-Time 2.8 中,如果您不关心时间,请使用

LocalDate
类。

LocalDate today = LocalDate.now( DateTimeZone.forID( "Europe/Paris" ) );
LocalDate firstOfThisMonth = today.withDayOfMonth( 1 );
LocalDate firstOfLastMonth = firstOfThisMonth.minusMonths( 1 );
LocalDate endOfLastMonth = firstOfThisMonth.minusDays( 1 );

关于 java.time

java.time框架内置于 Java 8 及更高版本中。这些类取代了麻烦的旧legacy日期时间类,例如

java.util.Date
Calendar
SimpleDateFormat

Joda-Time项目现在处于维护模式,建议迁移到java.time类。

要了解更多信息,请参阅 Oracle 教程。并在 Stack Overflow 上搜索许多示例和解释。规格为JSR 310

您可以直接与数据库交换 java.time 对象。使用符合 JDBC 4.2 或更高版本的 JDBC 驱动程序。不需要字符串,不需要

java.sql.*
类。

从哪里获取java.time类?

ThreeTen-Extra 项目通过附加类扩展了 java.time。该项目是 java.time 未来可能添加的内容的试验场。您可能会在这里找到一些有用的类,例如

Interval
YearWeek
YearQuarter
more


4
投票

使用JodaTime

DateMidnight now = new DateMidnight();
DateMidnight beginningOfLastMonth = now.minusMonths(1).withDayOfMonth(1);
DateMidnight endOfLastMonth = now.withDayOfMonth(1).minusDays(1);
System.out.println(beginningOfLastMonth);
System.out.println(endOfLastMonth);

输出:

2012-04-01T00:00:00.000+02:00
2012-04-30T00:00:00.000+02:00

说明:DateMidnight 对象是一个没有时间信息的日期对象,这似乎正是您所需要的。如果没有,请将上述代码中所有出现的 DateMidnight 替换为 DateTime。


3
投票

您可以创建一个日历对象,将日期设置为当月的第一天(应该是第一天:P),然后您可以执行两个操作: 您可以从日历对象中减去特定的时间段,例如一个月(这会给你上个月的第一个日期,或者一天,这会给你上个月的最后一天。我没有尝试过,但这将是我的第一步。


2
投票

还想在 Jigar 的答案中添加一些内容。使用

DateFormat
类以您在问题中指定的格式获取日期:

DateFormat df = DateFormat.getInstance(DateFormat.SHORT);
System.out.println(df.format(firstDateOfPreviousMonth));
System.out.println(df.format(lastDateOfPreviousMonth));

输出:

04/01/12
04/30/12

2
投票
public static LocalDate getPreviousMonthStartDate() {

    return LocalDate.now().minusMonths(1).with(TemporalAdjusters.firstDayOfMonth());
}

public static LocalDate getPreviousMonthLastDate() {

    return LocalDate.now().minusMonths(1).with(TemporalAdjusters.lastDayOfMonth());
}

使用Java.Time编写代码非常容易。 java.time 包具有更好的设计,更线程安全,许多实用方法来支持常见操作,并且可以使用 Local 和 ZonedDate/Time API 轻松处理时区。


2
投票

//在模式中您可以使用您想要的格式。

  DateTimeFormatter format = DateTimeFormatter.ofPattern("MM/dd/yyyy");
                LocalDate now = LocalDate.now();
                String startDate = now.minusMonths(1).with(TemporalAdjusters.firstDayOfMonth()).format(format);
                String endDate = now.minusMonths(1).with(TemporalAdjusters.lastDayOfMonth()).format(format);

1
投票
    Calendar cal = Calendar.getInstance();
    cal.set(Calendar.DATE, 1);
    cal.add(Calendar.DAY_OF_MONTH, -1);
    Date lastDateOfPreviousMonth = cal.getTime();
    cal.set(Calendar.DATE, 1);
    Date firstDateOfPreviousMonth = cal.getTime();

1
投票
    public List customizeDate(String month, int year) {
        List<String> list = new ArrayList<String>();
        try {
            String edates = null;
            String sdates = null;
            if (month.equals("JAN") || month.equals("MAR") ||
                month.equals("MAY") || month.equals("JUL") ||
                month.equals("AUG") || month.equals("OCT") ||
                month.equals("DEC")) {
                String s1 = "01";
                String s2 = "31";

                String sdate = s1 + "-" + month + "-" + year;
                System.out.println("Startdate" + sdate);
                SimpleDateFormat sd = new SimpleDateFormat("dd-MMM-yyyy");
                Date ed = sd.parse(sdate);
                sdates = sd.format(ed);
                System.out.println("ed" + ed + "------------" + sdates);
                String endDate = s2 + "-" + month + "-" + year;
                System.out.println("EndDate" + endDate);
                SimpleDateFormat s = new SimpleDateFormat("dd-MMM-yyyy");
                Date d = s.parse(endDate);
                edates = s.format(d);
                System.out.println("d" + d + "------------" + edates);
            } else if (month.equals("APR") || month.equals("JUN") ||
                       month.equals("SEP") || month.equals("NOV")) {
                String s3 = "01";
                String s4 = "30";
                String sdate = s3 + "-" + month + "-" + year;
                System.out.println("Startdate" + sdate);
                SimpleDateFormat sd = new SimpleDateFormat("dd-MMM-yyyy");
                Date ed = sd.parse(sdate);
                sdates = sd.format(ed);
                System.out.println("ed" + ed + "------------" + sdates);
                String endDate = s4 + "-" + month + "-" + year;
                System.out.println("EndDate" + endDate);
                SimpleDateFormat s = new SimpleDateFormat("dd-MMM-yyyy");
                Date d = s.parse(endDate);
                edates = s.format(d);
                System.out.println("d" + d + "------------" + edates);
            } else {
                if (year % 4 == 0 && year % 100 != 0 || year % 400 == 0) {
                    System.out.println("Leap year");
                    if (month.equals("FEB")) {
                        String s5 = "01";
                        String s6 = "29";
                        String sdate = s5 + "-" + month + "-" + year;
                        System.out.println("Startdate" + sdate);
                        SimpleDateFormat sd =
                            new SimpleDateFormat("dd-MMM-yyyy");
                        Date ed = sd.parse(sdate);
                        sdates = sd.format(ed);
                        System.out.println("ed" + ed + "------------" +
                                           sdates);
                        String endDate = s6 + "-" + month + "-" + year;
                        System.out.println("EndDate" + endDate);
                        SimpleDateFormat s =
                            new SimpleDateFormat("dd-MMM-yyyy");
                        Date d = s.parse(endDate);
                        edates = s.format(d);
                        System.out.println("d" + d + "------------" + edates);
                    }
                } else {
                    System.out.println("Not a leap year");
                    String s7 = "01";
                    String s8 = "28";
                    String sdate = s7 + "-" + month + "-" + year;
                    System.out.println("Startdate" + sdate);
                    SimpleDateFormat sd = new SimpleDateFormat("dd-MMM-yyyy");
                    Date ed = sd.parse(sdate);
                    sdates = sd.format(ed);
                    System.out.println("ed" + ed + "------------" + sdates);
                    String endDate = s8 + "-" + month + "-" + year;
                    System.out.println("EndDate" + endDate);
                    SimpleDateFormat s = new SimpleDateFormat("dd-MMM-yyyy");
                    Date d = s.parse(endDate);
                    edates = s.format(d);
                    System.out.println("d" + d + "------------" + edates);
                }
            }
            list.add(edates);
            list.add(sdates);
        } catch (Exception e) {
            System.err.println(e.getMessage());
        }
        return list;
    }
}

0
投票

类似于如何获取当前月份的第一天

    LocalDate.now().minusMonths(1)
         .with( TemporalAdjusters.firstDayOfMonth() );

    LocalDate.now().minusMonths(1)
         .with( TemporalAdjusters.lastDayOfMonth() );
© www.soinside.com 2019 - 2024. All rights reserved.