如何获得当前星期和月份的第一天?


76

我有几个事件的日期,以毫秒[1]表示,我想知道哪些事件在当前周和本月内,但是我不知道如何获取第一天(天/月/年) ),并将其转换为毫秒,与该月的第一天相同。

[1]Since January 1, 1970, 00:00:00 GMT

7
如何获得每月的第一天?这是一个编号1...
迈克尔Mrozek

是的,但是如何获取每月第一天的名称?
Goran Horia Mihail 2014年

Answers:


163

本周(以毫秒为单位):

// get today and clear time of day
Calendar cal = Calendar.getInstance();
cal.set(Calendar.HOUR_OF_DAY, 0); // ! clear would not reset the hour of day !
cal.clear(Calendar.MINUTE);
cal.clear(Calendar.SECOND);
cal.clear(Calendar.MILLISECOND);

// get start of this week in milliseconds
cal.set(Calendar.DAY_OF_WEEK, cal.getFirstDayOfWeek());
System.out.println("Start of this week:       " + cal.getTime());
System.out.println("... in milliseconds:      " + cal.getTimeInMillis());

// start of the next week
cal.add(Calendar.WEEK_OF_YEAR, 1);
System.out.println("Start of the next week:   " + cal.getTime());
System.out.println("... in milliseconds:      " + cal.getTimeInMillis());

本月(以毫秒为单位):

// get today and clear time of day
Calendar cal = Calendar.getInstance();
cal.set(Calendar.HOUR_OF_DAY, 0); // ! clear would not reset the hour of day !
cal.clear(Calendar.MINUTE);
cal.clear(Calendar.SECOND);
cal.clear(Calendar.MILLISECOND);

// get start of the month
cal.set(Calendar.DAY_OF_MONTH, 1);
System.out.println("Start of the month:       " + cal.getTime());
System.out.println("... in milliseconds:      " + cal.getTimeInMillis());

// get start of the next month
cal.add(Calendar.MONTH, 1);
System.out.println("Start of the next month:  " + cal.getTime());
System.out.println("... in milliseconds:      " + cal.getTimeInMillis());

一天的开始还需要清除am_pm cal.clear(Calendar.AM_PM);
凯欣2012年

@keshin:是的。我更换了线条cal.clear(Calendar.HOUR_OF_DAY);cal.set(Calendar.HOUR_OF_DAY, 0);类似指示在日历的javadoc的。

1
@COMEFROM为什么您建议使用clear?如果我使用,会有什么好处?如果不使用,会出现什么错误?
SpringLearner 2015年

@SpringLearner:几天,几周,几个月都在午夜开始和结束。但是,Calendar.getInstance通常不返回指向午夜(00:00:00.000)的Calendar实例。因此,要找出一天的开始或结束(或一周或一个月),需要重置一天中的时间。

@COMEFROM连我自己都不那么清楚也是它的工作所以只是想知道为什么你来了
SpringLearner

25

可以借助以下方法确定一周的第一天java.util.Calendar

Calendar calendar = Calendar.getInstance();
calendar.clear();
calendar.setTimeInMillis(timestamp);
while (calendar.get(Calendar.DAY_OF_WEEK) > calendar.getFirstDayOfWeek()) {
    calendar.add(Calendar.DATE, -1); // Substract 1 day until first day of week.
}
long firstDayOfWeekTimestamp = calendar.getTimeInMillis();

可以确定月份的第一天如下:

Calendar calendar = Calendar.getInstance();
calendar.clear();
calendar.setTimeInMillis(timestamp);
while (calendar.get(Calendar.DATE) > 1) {
    calendar.add(Calendar.DATE, -1); // Substract 1 day until first day of month.
}
long firstDayOfMonthTimestamp = calendar.getTimeInMillis();

很冗长,是的。


Java 7将带有大大改进的Date and Time API(JSR-310)。如果您还不能切换,那么可以使用JodaTime,这使它变得不那么复杂:

DateTime dateTime = new DateTime(timestamp);
long firstDayOfWeekTimestamp = dateTime.withDayOfWeek(1).getMillis();

DateTime dateTime = new DateTime(timestamp);
long firstDayOfMonthTimestamp = dateTime.withDayOfMonth(1).getMillis();

1
非常感谢,我正在一个全新的世界Java上开发我的第一个Android应用程序,我从没听说过joda,但我不确定joda + android。再次感谢!
cesarlinux

1
别客气。使用JodaTime只是下载JAR并将其放在类路径中。与其他所有“第三方”库一样。
BalusC,2010年

@cesar,您在问题中或在标记中指出这是针对Android的吗?
Paul Tomblin

2
尽管请记住,jodatime可能会将您的30kb应用程序变成300kb应用程序。
flodin 2010年

好答案。我建议还将DateTimeZone对象传递给DateTime构造函数,而不是隐式依赖于JVM的当前默认时区进行分配。
罗勒·布尔克

18

java.time

Java 8和更高版本中的java.time框架取代了旧的java.util.Date/.Calendar类。老类被证明是麻烦,混乱和有缺陷的。避免他们。

java.time框架的灵感来自于JSR 310定义的,由ThreeTen-Extra项目扩展的,非常成功的Joda-Time库,并在Tutorial中进行了说明。

Instant

Instant课程代表UTC时间轴上的一个时刻。

java.time框架的分辨率为纳秒,即9位数的分数。毫秒仅是小数秒的3位数字。因为毫秒分辨率是常见的,所以java.time包含了一个方便的工厂方法。

long millisecondsSinceEpoch = 1446959825213L;
Instant instant = Instant.ofEpochMilli ( millisecondsSinceEpoch );

millisecondsSinceEpoch:1446959825213是即时的:2015-11-08T05:17:05.213Z

ZonedDateTime

要考虑当前星期和当前月份,我们需要应用特定的时区。

ZoneId zoneId = ZoneId.of ( "America/Montreal" );
ZonedDateTime zdt = ZonedDateTime.ofInstant ( instant , zoneId );

在zoneId:美国/蒙特利尔,即:2015-11-08T00:17:05.213-05:00 [美国/蒙特利尔]

半开

在日期时间工作中,我们通常使用“半开放式”方法来定义时间跨度。开始是包容性的,而结尾是排他性的。而不是尝试确定一周(或月份)末尾的最后一秒钟,而是获得一周(或月份)的第一时刻。所以一个星期从周一的第一时刻运行,并上升到但不包括在第一时刻以下星期一。

让我们开始一周的第一天,最后一天。java.time框架包括用于此目的的工具,with方法和ChronoField枚举。

默认情况下,java.time使用ISO 8601标准。因此,星期一是一周的第一天(1),而星期日是最后一天(7)。

ZonedDateTime firstOfWeek = zdt.with ( ChronoField.DAY_OF_WEEK , 1 ); // ISO 8601, Monday is first day of week.
ZonedDateTime firstOfNextWeek = firstOfWeek.plusWeeks ( 1 );

该周从:2015-11-02T00:17:05.213-05:00 [美国/蒙特利尔]到2015-11-09T00:17:05.213-05:00 [美国/蒙特利尔]

糟糕!查看这些值在一天中的时间。我们想要一天的第一刻。一天的第一时刻并不总是00:00:00.000因为夏令时(DST)或其他异常。因此,我们应该让java.time代表我们进行调整。为此,我们必须遍历LocalDate全班。

ZonedDateTime firstOfWeek = zdt.with ( ChronoField.DAY_OF_WEEK , 1 ); // ISO 8601, Monday is first day of week.
firstOfWeek = firstOfWeek.toLocalDate ().atStartOfDay ( zoneId );
ZonedDateTime firstOfNextWeek = firstOfWeek.plusWeeks ( 1 );

该周从:2015-11-02T00:00-05:00 [美国/蒙特利尔]到2015-11-09T00:00-05:00 [美国/蒙特利尔]

和一个月相同。

ZonedDateTime firstOfMonth = zdt.with ( ChronoField.DAY_OF_MONTH , 1 );
firstOfMonth = firstOfMonth.toLocalDate ().atStartOfDay ( zoneId );
ZonedDateTime firstOfNextMonth = firstOfMonth.plusMonths ( 1 );

该月从:2015-11-01T00:00-04:00 [美国/蒙特利尔]到2015-12-01T00:00-05:00 [美国/蒙特利尔]

YearMonth

查看一对月份是否在同一个月中的另一种方法是检查相同的YearMonth值。

例如,假设thisZdtthatZdt都是ZonedDateTime对象:

boolean inSameMonth = YearMonth.from( thisZdt ).equals( YearMonth.from( thatZdt ) ) ;

毫秒

我强烈建议您不要以毫秒为单位进行日期时间工作。这确实是日期时间类倾向于在内部工作的方式,但是我们之所以有这些类是有原因的。由于人们无法理解这些值,因此很难计算时间,因此调试和记录非常困难且容易出错。而且,正如我们已经看到的,不同的分辨率可能会起作用。旧的Java类和Joda-Time库使用毫秒,而Postgres之类的数据库使用毫秒,而现在的java.time使用纳秒。

你会处理文本作为位,还是你让类,如StringStringBufferStringBuilder处理这样的细节?

但是,如果您坚持要求,则从ZonedDateTime获得Instant,然后从那个获得毫秒数。但是请记住,此调用可能意味着数据丢失。您ZonedDateTime/中可能存在的任何微秒或纳秒都Instant将被截断(丢失)。

long millis = firstOfWeek.toInstant().toEpochMilli();  // Possible data loss.

关于java.time

java.time框架是建立在Java 8和更高版本。这些类取代麻烦的老传统日期时间类,如java.util.DateCalendar,和SimpleDateFormat

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

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

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

在哪里获取java.time类?


14

注意!

while (calendar.get(Calendar.DAY_OF_WEEK) > calendar.getFirstDayOfWeek()) {
    calendar.add(Calendar.DATE, -1); // Substract 1 day until first day of week.
}

是个好主意,但有一些问题:例如,我来自乌克兰,我所在国家的calendar.getFirstDayOfWeek()为2(星期一)。今天是1(星期日)。在这种情况下,不会调用calendar.add。

因此,正确的方法是将“>”更改为“!=”:

while (calendar.get(Calendar.DAY_OF_WEEK) != calendar.getFirstDayOfWeek()) {...

3

要获取该月的第一天,只需获取aDate并将当前日期设置为该月的第一天。如果需要,请清除小时,分钟,秒和毫秒。

private static Date firstDayOfMonth(Date date) {
   Calendar calendar = Calendar.getInstance();
   calendar.setTime(date);
   calendar.set(Calendar.DATE, 1);
   return calendar.getTime();
}

一周的第一天是一回事,但Calendar.DAY_OF_WEEK改用

private static Date firstDayOfWeek(Date date) {
   Calendar calendar = Calendar.getInstance();
   calendar.setTime(date);
   calendar.set(Calendar.DAY_OF_WEEK, 1);
   return calendar.getTime();
}

您能提供关于如何提取所选日期所在的一周中所有天的任何建议吗?
严格执行

import java.time.DayOfWeek; DayOfWeek[] daysOfWeek = DayOfWeek.values();
Ilja Tarasovs

2

我为此创建了一些方法:

public static String catchLastDayOfCurrentWeek(String pattern) {
    Calendar cal = Calendar.getInstance();
    cal.set(Calendar.HOUR_OF_DAY, 0);
    cal.clear(Calendar.MINUTE);
    cal.clear(Calendar.SECOND);
    cal.clear(Calendar.MILLISECOND);

    cal.set(Calendar.DAY_OF_WEEK, cal.getFirstDayOfWeek());

    return calendarToString(cal, pattern);
}

public static String catchLastDayOfCurrentWeek(String pattern) {
    Calendar cal = Calendar.getInstance();
    cal.set(Calendar.HOUR_OF_DAY, 0);
    cal.clear(Calendar.MINUTE);
    cal.clear(Calendar.SECOND);
    cal.clear(Calendar.MILLISECOND);

    cal.set(Calendar.DAY_OF_WEEK, cal.getFirstDayOfWeek());

    cal.add(Calendar.WEEK_OF_YEAR, 1);
    cal.add(Calendar.MILLISECOND, -1);

    return calendarToString(cal, pattern);
}

public static String catchTheFirstDayOfThemonth(Integer month, pattern padrao) {
    Calendar cal = GregorianCalendar.getInstance();
    cal.setTime(new Date());
    cal.set(Calendar.MONTH, month);
    cal.set(Calendar.DAY_OF_MONTH, 1);

    return calendarToString(cal, pattern);
}

public static String catchTheLastDayOfThemonth(Integer month, String pattern) {
    Calendar cal = GregorianCalendar.getInstance();
    cal.setTime(new Date());
    cal.set(cal.get(Calendar.YEAR), month, cal.getActualMaximum(Calendar.DAY_OF_MONTH));

    return calendarToString(cal, pattern);
}

public static String calendarToString(Calendar calendar, String pattern) {
    if (calendar == null) {
        return "";
    }
    SimpleDateFormat format = new SimpleDateFormat(pattern, LocaleUtils.DEFAULT_LOCALE);
    return format.format(calendar.getTime());
}

你可以在这里看到更多。


2

您可以使用该java.time软件包(从Java8开始和以后)来获取日期/星期/月份的开始/结束时间。
下面的util类示例:

import org.junit.Test;

import java.time.DayOfWeek;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.time.temporal.TemporalAdjusters;
import java.util.Date;

public class DateUtil {
    private static final ZoneId DEFAULT_ZONE_ID = ZoneId.of("UTC");

    public static LocalDateTime startOfDay() {
        return LocalDateTime.now(DEFAULT_ZONE_ID).with(LocalTime.MIN);
    }

    public static LocalDateTime endOfDay() {
        return LocalDateTime.now(DEFAULT_ZONE_ID).with(LocalTime.MAX);
    }

    public static boolean belongsToCurrentDay(final LocalDateTime localDateTime) {
        return localDateTime.isAfter(startOfDay()) && localDateTime.isBefore(endOfDay());
    }

    //note that week starts with Monday
    public static LocalDateTime startOfWeek() {
        return LocalDateTime.now(DEFAULT_ZONE_ID)
                .with(LocalTime.MIN)
                .with(TemporalAdjusters.previousOrSame(DayOfWeek.MONDAY));
    }

    //note that week ends with Sunday
    public static LocalDateTime endOfWeek() {
        return LocalDateTime.now(DEFAULT_ZONE_ID)
                .with(LocalTime.MAX)
                .with(TemporalAdjusters.nextOrSame(DayOfWeek.SUNDAY));
    }

    public static boolean belongsToCurrentWeek(final LocalDateTime localDateTime) {
        return localDateTime.isAfter(startOfWeek()) && localDateTime.isBefore(endOfWeek());
    }

    public static LocalDateTime startOfMonth() {
        return LocalDateTime.now(DEFAULT_ZONE_ID)
                .with(LocalTime.MIN)
                .with(TemporalAdjusters.firstDayOfMonth());
    }

    public static LocalDateTime endOfMonth() {
        return LocalDateTime.now(DEFAULT_ZONE_ID)
                .with(LocalTime.MAX)
                .with(TemporalAdjusters.lastDayOfMonth());
    }

    public static boolean belongsToCurrentMonth(final LocalDateTime localDateTime) {
        return localDateTime.isAfter(startOfMonth()) && localDateTime.isBefore(endOfMonth());
    }

    public static long toMills(final LocalDateTime localDateTime) {
        return localDateTime.atZone(DEFAULT_ZONE_ID).toInstant().toEpochMilli();
    }

    public static Date toDate(final LocalDateTime localDateTime) {
        return Date.from(localDateTime.atZone(DEFAULT_ZONE_ID).toInstant());
    }

    public static String toString(final LocalDateTime localDateTime) {
        return localDateTime.format(DateTimeFormatter.ISO_DATE_TIME);
    }

    @Test
    public void test() {
        //day
        final LocalDateTime now = LocalDateTime.now();
        System.out.println("Now: " + toString(now) + ", in mills: " + toMills(now));
        System.out.println("Start of day: " + toString(startOfDay()));
        System.out.println("End of day: " + toString(endOfDay()));
        System.out.println("Does '" + toString(now) + "' belong to the current day? > " + belongsToCurrentDay(now));
        final LocalDateTime yesterday = now.minusDays(1);
        System.out.println("Does '" + toString(yesterday) + "' belong to the current day? > " + belongsToCurrentDay(yesterday));
        final LocalDateTime tomorrow = now.plusDays(1);
        System.out.println("Does '" + toString(tomorrow) + "' belong to the current day? > " + belongsToCurrentDay(tomorrow));
        //week
        System.out.println("Start of week: " + toString(startOfWeek()));
        System.out.println("End of week: " + toString(endOfWeek()));
        System.out.println("Does '" + toString(now) + "' belong to the current week? > " + belongsToCurrentWeek(now));
        final LocalDateTime previousWeek = now.minusWeeks(1);
        System.out.println("Does '" + toString(previousWeek) + "' belong to the current week? > " + belongsToCurrentWeek(previousWeek));
        final LocalDateTime nextWeek = now.plusWeeks(1);
        System.out.println("Does '" + toString(nextWeek) + "' belong to the current week? > " + belongsToCurrentWeek(nextWeek));
        //month
        System.out.println("Start of month: " + toString(startOfMonth()));
        System.out.println("End of month: " + toString(endOfMonth()));
        System.out.println("Does '" + toString(now) + "' belong to the current month? > " + belongsToCurrentMonth(now));
        final LocalDateTime previousMonth = now.minusMonths(1);
        System.out.println("Does '" + toString(previousMonth) + "' belong to the current month? > " + belongsToCurrentMonth(previousMonth));
        final LocalDateTime nextMonth = now.plusMonths(1);
        System.out.println("Does '" + toString(nextMonth) + "' belong to the current month? > " + belongsToCurrentMonth(nextMonth));
    }
}

测试输出:

Now: 2020-02-16T22:12:49.957, in mills: 1581891169957
Start of day: 2020-02-16T00:00:00
End of day: 2020-02-16T23:59:59.999999999
Does '2020-02-16T22:12:49.957' belong to the current day? > true
Does '2020-02-15T22:12:49.957' belong to the current day? > false
Does '2020-02-17T22:12:49.957' belong to the current day? > false
Start of week: 2020-02-10T00:00:00
End of week: 2020-02-16T23:59:59.999999999
Does '2020-02-16T22:12:49.957' belong to the current week? > true
Does '2020-02-09T22:12:49.957' belong to the current week? > false
Does '2020-02-23T22:12:49.957' belong to the current week? > false
Start of month: 2020-02-01T00:00:00
End of month: 2020-02-29T23:59:59.999999999
Does '2020-02-16T22:12:49.957' belong to the current month? > true
Does '2020-01-16T22:12:49.957' belong to the current month? > false
Does '2020-03-16T22:12:49.957' belong to the current month? > false

感谢您的详尽演示。两个建议:(1)不想ZonedDateTimeOffsetDateTime用于一个日期和时间需要以表示在时间轴上的固定点。(2)将一天的结束时间定义为第二天的第一时刻(不包括在内),将一天(并因此将周和月)定义为半开放时间间隔。这样做更正确(不排除一天中的最后一纳秒),有时还会提供更简单的代码。
Ole VV

1

在这种情况下:

// get today and clear time of day
Calendar cal = Calendar.getInstance();
cal.clear(Calendar.HOUR_OF_DAY);  <---- is the current hour not 0 hour
cal.clear(Calendar.MINUTE);
cal.clear(Calendar.SECOND);
cal.clear(Calendar.MILLISECOND);

因此,Calendar.HOUR_OF_DAY返回8、9、12、15、18作为当前运行时间。我认为通过以下方式更改此类行会更好:

c.set(Calendar.HOUR_OF_DAY,0);

这样,一天总是从0小时开始


1

获取下个月的第一个日期:-

SimpleDateFormat df = new SimpleDateFormat("MM-dd-yyyy");
String selectedDate="MM-dd-yyyy like 07-02-2018";
Date dt = df.parse(selectedDate);`enter code here`
calendar = Calendar.getInstance();
calendar.setTime(dt);
calendar.set(Calendar.DAY_OF_MONTH, calendar.getActualMaximum(Calendar.DAY_OF_MONTH) + 1);

String firstDate = df.format(calendar.getTime());
System.out.println("firstDateof next month ==>" + firstDate);

0

您应该能够将您的号码转换为Java日历,例如:

 Calendar.getInstance().setTimeInMillis(myDate);

从那里开始,比较不应该太难。


0
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.GregorianCalendar;
import java.util.Scanner;

/**
This Program will display day for, 1st and last days in a given month and year

@author Manoj Kumar Dunna
Mail Id : manojdunna@gmail.com
*/
public class DayOfWeek {
    public static void main(String[] args) {
        String strDate = null;
        int  year = 0, month = 0;
        Scanner sc = new Scanner(System.in);
        System.out.print("Enter YYYY/MM: ");
        strDate = sc.next();
        Calendar cal = new GregorianCalendar();
        String [] date = strDate.split("/");
        year = Integer.parseInt(date[0]);
        month = Integer.parseInt(date[1]);
        cal.set(year, month-1, 1);
        System.out.println(new SimpleDateFormat("EEEE").format(cal.getTime()));
        cal.add(Calendar.MONTH, 1);
        cal.add(Calendar.DAY_OF_YEAR, -1);
        System.out.println(new SimpleDateFormat("EEEE").format(cal.getTime()));
    }
}

0
Simple Solution:
package com.util.calendarutil;

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

public class CalUtil {
    public static void main(String args[]){
        DateFormat df = new SimpleDateFormat("dd/mm/yyyy");
        Date dt = null;
        try {
            dt = df.parse("23/01/2016");
        } catch (ParseException e) {
            System.out.println("Error");
        }

        Calendar cal = Calendar.getInstance();
        cal.setTime(dt);
        cal.set(Calendar.DAY_OF_WEEK, cal.getFirstDayOfWeek());
        Date startDate = cal.getTime();
        cal.add(Calendar.DATE, 6);
        Date endDate = cal.getTime();
        System.out.println("Start Date:"+startDate+"End Date:"+endDate);


    }

}

0

使用Java 8功能的单线解决方案

Java中

LocalDateTime firstOfWeek = LocalDateTime.now().with(ChronoField.DAY_OF_WEEK, 1).toLocalDate().atStartOfDay(); // 2020-06-08 00:00 MONDAY
LocalDateTime firstOfMonth = LocalDateTime.now().with(ChronoField.DAY_OF_MONTH , 1).toLocalDate().atStartOfDay(); // 2020-06-01 00:00
// Convert to milliseconds: 
firstOfWeek.atZone(ZoneId.systemDefault()).toInstant().toEpochMilli();

科特林

val firstOfWeek = LocalDateTime.now().with(ChronoField.DAY_OF_WEEK, 1).toLocalDate().atStartOfDay() // 2020-06-08 00:00 MONDAY
val firstOfMonth = LocalDateTime.now().with(ChronoField.DAY_OF_MONTH , 1).toLocalDate().atStartOfDay() // 2020-06-01 00:00
// Convert to milliseconds: 
firstOfWeek.atZone(ZoneId.systemDefault()).toInstant().toEpochMilli()

关于如何LocalDateTime轻松转换为毫秒的任何想法?
丹尼尔(Daniel)

1
嗯,所以您的想法是比较毫秒值?我更愿意比较Instant使用它们的对象isBeforeisEqualisAfter方法。您从那里得到了短暂的收获Instant.ofEpochMilli(someMillisecondValue)。是的,转换a的更简单方法LocalDateTimefirstOfWeek.atZone(ZoneId.systemDefault()).toInstant()
Ole VV

-1

我使用这个技巧来获取当前月份的第一天,注意顺序是星期二2为1,星期二3为星期一....依此类推

Calendar cal = new GregorianCalendar();
int startDay = cal.get(Calendar.DAY_OF_YEAR) % 7 + 1;
System.out.println(startDay);

1
仅供参考,麻烦的日期时间类,如java.util.Datejava.util.Calendarjava.text.SimpleDateFormat现在的遗产,由取代java.time类。在ThreeTen-Backport项目中,大多数java.time功能都被反向移植到Java 6和Java 7 。在ThreeTenABP中进一步适用于早期的Android(<26)。请参阅如何使用ThreeTenABP…
罗勒·布尔克

我不认为您正在回答这个问题。也许是另一个问题。
Ole VV

它也不起作用。今天运行您的代码,星期三,我得到了3,根据您的意见,应该是星期二。
Ole VV

-4
public static void main(String[] args) {
    System.out.println(getMonthlyEpochList(1498867199L,12,"Monthly"));

}

public static Map<String,String> getMonthlyEpochList(Long currentEpoch, int noOfTerms, String timeMode) {
    Map<String,String> map = new LinkedHashMap<String,String>();
    int month = 0;
    while(noOfTerms != 0) {
        Calendar calendar = Calendar.getInstance();         
        calendar.add(Calendar.MONTH, month);
        calendar.set(Calendar.DATE, calendar.getActualMinimum(Calendar.DAY_OF_MONTH));
        Date monthFirstDay = calendar.getTime();
        calendar.set(Calendar.DATE, calendar.getActualMaximum(Calendar.DAY_OF_MONTH));
        Date monthLastDay = calendar.getTime();
        map.put(getMMYY(monthFirstDay.getTime()), monthFirstDay + ":" +monthLastDay);
        month--;
        noOfTerms--;
    }
    return map;     
}

3
您能告诉我们为什么要添加这个作为答案吗?
birwin

仅供参考,麻烦的旧日期,时间类,如java.util.Datejava.util.Calendarjava.text.SimpleTextFormat现在的遗产,由取代java.time类。请参见Oracle教程
罗勒·布尔克
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.