繁体   English   中英

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

[英]How to get the first date and last date of the previous month? (Java)

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

例如,通过05/30/2012 ,我应该得到04/01/201204/30/2012

任何帮助都感激不尽。 谢谢。

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();

tl;博士

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

…和…

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

避免 juDate

避免使用捆绑的java.util.Date.Calendar类,因为它们是出了名的麻烦。 相反,在 Java 8 及更高版本中使用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 及更高版本中。 这些类取代麻烦的老传统日期时间类,如java.util.DateCalendar ,和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 的试验场。 您可以在这里找到一些有用的类,比如IntervalYearWeekYearQuarter ,和更多

使用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 对象是一个没有时间信息的 Date 对象,这似乎正是您所需要的。 如果不是,请将上述代码中所有出现的 DateMidnight 替换为 DateTime。

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

还想在 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
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 处理时区。

//在模式中,您可以使用所需的格式。

  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);
    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();
    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;
    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM