如何获得当周和当月的第一天?

时间:2022-10-21 10:48:27

I have the date of several events expressed in milliseconds[1], and I want to know which events are inside the current week and the current month, but I can't figure out how to obtain the first day (day/month/year) of the running week and convert it to milliseconds, the same for the first day of the month.

我有几个事件的日期用毫秒表示[1],我想知道哪些事件是在当前的星期和当前月份,但我不知道如何获得第一天(日/月/年)的运行,将其转换为毫秒,相同的第一天。

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

12 个解决方案

#1


118  

This week in milliseconds:

本周以毫秒为单位:

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

This month in milliseconds:

本月以毫秒为单位:

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

#2


22  

The first day of week can be determined with help of java.util.Calendar as follows:

在java.util的帮助下可以确定一周的第一天。日程如下:

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

The first day of month can be determined as follows:

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

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

Pretty verbose, yes.

很详细的,是的。


Java 7 will come with a much improved Date and Time API (JSR-310). If you can't switch yet, then you can as far use JodaTime which makes it all less complicated:

Java 7将提供一个改进后的日期和时间API (JSR-310)。如果你还不能切换,那么你可以使用JodaTime,这样就不那么复杂了:

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

and

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

#3


11  

Attention!

注意!

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

is good idea, but there is some issue: For example, i'm from Ukraine and calendar.getFirstDayOfWeek() in my country is 2 (Monday). And today is 1 (Sunday). In this case calendar.add not called.

是一个好主意,但是有一些问题:例如,我来自乌克兰和日历。今天是星期天。在这种情况下日历。添加不叫。

So, correct way is change ">" to "!=":

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

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

#4


10  

java.time

The java.time framework in Java 8 and later supplants the old java.util.Date/.Calendar classes. The old classes have proven to be troublesome, confusing, and flawed. Avoid them.

java。Java 8中的时间框架,后来取代了旧的Java .util. date /。日历类。旧的类被证明是麻烦的、混乱的和有缺陷的。避免它们。

The java.time framework is inspired by the highly-successful Joda-Time library, defined by JSR 310, extended by the ThreeTen-Extra project, and explained in the Tutorial.

java。time框架的灵感来自于成功的Joda-Time库,由JSR 310定义,由三个额外的项目扩展,并在本教程中进行了解释。

Instant

The Instant class represents a moment on the timeline in UTC.

Instant类表示UTC时间轴上的一个时刻。

The java.time framework has a resolution of nanoseconds, or 9 digits of a fractional second. Milliseconds is only 3 digits of a fractional second. Because millisecond resolution is common, java.time includes a handy factory method.

java。时间框架的分辨率为纳秒,或9位数的几分之一秒。毫秒仅仅是三位数的几分之一秒。因为毫秒级的分辨率很常见,java。时间包括一个方便的工厂方法。

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

millisecondsSinceEpoch: 1446959825213 is instant: 2015-11-08T05:17:05.213Z

毫秒:1446959825213 is instant: 2015-11-08t05:05:05.213

ZonedDateTime

To consider current week and current month, we need to apply a particular time zone.

要考虑当前周和当前月,我们需要应用一个特定的时区。

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

In zoneId: America/Montreal that is: 2015-11-08T00:17:05.213-05:00[America/Montreal]

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

Half-Open

In date-time work, we commonly use the Half-Open approach to defining a span of time. The beginning is inclusive while the ending in exclusive. Rather than try to determine the last split-second of the end of the week (or month), we get the first moment of the following week (or month). So a week runs from the first moment of Monday and goes up to but not including the first moment of the following Monday.

在日期-时间工作中,我们通常使用半开放的方法来定义时间跨度。开头是包容的,结尾是排他性的。与其试图确定一周(或一个月)的最后一秒,不如选择下一周(或下个月)的第一个时刻。一周从周一的第一个时刻开始,一直持续到下周一的第一个时刻。

Let's the first day of the week, and last. The java.time framework includes a tool for that, the with method and the ChronoField enum.

让我们从一周的第一天开始,到最后一天。java。时间框架包括一个工具,与方法和时域枚举。

By default, java.time uses the ISO 8601 standard. So Monday is the first day of the week (1) and Sunday is last (7).

默认情况下,java。time使用ISO 8601标准。所以星期一是一周的第一天,星期天是最后一天。

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

That week runs from: 2015-11-02T00:17:05.213-05:00[America/Montreal] to 2015-11-09T00:17:05.213-05:00[America/Montreal]

那个星期从:2015-11-02T00:17:05.213-05:00[美国/蒙特利尔]到2015-11-09T00:17:05.213-05:00[美国/蒙特利尔]

Oops! Look at the time-of-day on those values. We want the first moment of the day. The first moment of the day is not always 00:00:00.000 because of Daylight Saving Time (DST) or other anomalies. So we should let java.time make the adjustment on our behalf. To do that, we must go through the LocalDate class.

哦!看看这些值的时间。我们想要一天中的第一个时刻。由于夏令时(DST)或其他异常情况,一天中的第一个时刻并不总是00:00. 00.000。所以我们应该让java。是时候代表我们做出调整了。为此,我们必须遍历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 );

That week runs from: 2015-11-02T00:00-05:00[America/Montreal] to 2015-11-09T00:00-05:00[America/Montreal]

这周的时间是:2015-11-02T00:00-05:00[美国/蒙特利尔]到2015-11-09T00:00-05:00[美国/蒙特利尔]

And same for the month.

这个月也一样。

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

That month runs from: 2015-11-01T00:00-04:00[America/Montreal] to 2015-12-01T00:00-05:00[America/Montreal]

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

YearMonth

Another way to see if a pair of moments are in the same month is to check for the same YearMonth value.

另一种查看两个时刻是否在同一个月的方法是检查相同年份的月值。

For example, assuming thisZdt and thatZdt are both ZonedDateTime objects:

例如,假设thisZdt和thatZdt都是ZonedDateTime对象:

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

Milliseconds

I strongly recommend against doing your date-time work in milliseconds-from-epoch. That is indeed the way date-time classes tend to work internally, but we have the classes for a reason. Handling a count-from-epoch is clumsy as the values are not intelligible by humans so debugging and logging is difficult and error-prone. And, as we've already seen, different resolutions may be in play; old Java classes and Joda-Time library use milliseconds, while databases like Postgres use microseconds, and now java.time uses nanoseconds.

我强烈建议你不要在距离日期毫秒的时间段内工作。这确实是日期-时间类在内部工作的方式,但是我们有这些类是有原因的。处理一个count-from-epoch的操作是很笨拙的,因为这些值是人类无法理解的,所以调试和日志记录是困难且容易出错的。正如我们已经看到的,不同的决议可能在起作用;旧的Java类和Joda-Time库使用毫秒,而像Postgres这样的数据库使用微秒,现在使用Java。使用纳秒的时间。

Would you handle text as bits, or do you let classes such as String, StringBuffer, and StringBuilder handle such details?

您是将文本作为位来处理,还是让字符串、StringBuffer和StringBuilder等类来处理这些细节?

But if you insist, from a ZonedDateTime get an Instant, and from that get a milliseconds-count-from-epoch. But keep in mind this call can mean loss of data. Any microseconds or nanoseconds that you might have in your ZonedDateTime/Instant will be truncated (lost).

但是如果你坚持的话,从ZonedDateTime得到一个瞬间,然后从中得到一个毫秒级的值。但请记住,这个调用可能意味着数据丢失。ZonedDateTime/Instant中的任何微秒或纳秒都将被截断(丢失)。

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

#5


2  

To get the first day of the month, simply get a Date and set the current day to day 1 of the month. Clear hour, minute, second and milliseconds if you need it.

要得到一个月的第一天,只需得到一个日期,并将当前的日期设置为每月的第一天。如果你需要的话,清理小时、分钟、秒和毫秒。

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

First day of the week is the same thing, but using Calendar.DAY_OF_WEEK instead

一周的第一天是一样的,但是使用日历。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();
}

#6


1  

In this case:

在这种情况下:

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

So the Calendar.HOUR_OF_DAY returns 8, 9, 12, 15, 18 as the current running hour. I think will be better change such line by:

因此,日历。HOUR_OF_DAY返回8,9,12,15,18作为当前运行小时。我想最好把这条线改为:

c.set(Calendar.HOUR_OF_DAY,0);

this way the day always begin at 0 hour

这样一天总是从0点开始

#7


0  

You should be able to convert your number to a Java Calendar, e.g.:

你应该能够把你的号码转换成Java日历,例如:

 Calendar.getInstance().setTimeInMillis(myDate);

From there, the comparison shouldn't be too hard.

从这一点来看,这种比较应该不会太难。

#8


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

#9


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


    }

}

#10


0  

I have created some methods for this:

我为此创造了一些方法:

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

You can see more here.

你可以在这里看到更多。

#11


0  

Get First date of next month:-

下个月的第一次约会:-。

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

#12


-3  

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

#1


118  

This week in milliseconds:

本周以毫秒为单位:

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

This month in milliseconds:

本月以毫秒为单位:

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

#2


22  

The first day of week can be determined with help of java.util.Calendar as follows:

在java.util的帮助下可以确定一周的第一天。日程如下:

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

The first day of month can be determined as follows:

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

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

Pretty verbose, yes.

很详细的,是的。


Java 7 will come with a much improved Date and Time API (JSR-310). If you can't switch yet, then you can as far use JodaTime which makes it all less complicated:

Java 7将提供一个改进后的日期和时间API (JSR-310)。如果你还不能切换,那么你可以使用JodaTime,这样就不那么复杂了:

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

and

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

#3


11  

Attention!

注意!

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

is good idea, but there is some issue: For example, i'm from Ukraine and calendar.getFirstDayOfWeek() in my country is 2 (Monday). And today is 1 (Sunday). In this case calendar.add not called.

是一个好主意,但是有一些问题:例如,我来自乌克兰和日历。今天是星期天。在这种情况下日历。添加不叫。

So, correct way is change ">" to "!=":

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

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

#4


10  

java.time

The java.time framework in Java 8 and later supplants the old java.util.Date/.Calendar classes. The old classes have proven to be troublesome, confusing, and flawed. Avoid them.

java。Java 8中的时间框架,后来取代了旧的Java .util. date /。日历类。旧的类被证明是麻烦的、混乱的和有缺陷的。避免它们。

The java.time framework is inspired by the highly-successful Joda-Time library, defined by JSR 310, extended by the ThreeTen-Extra project, and explained in the Tutorial.

java。time框架的灵感来自于成功的Joda-Time库,由JSR 310定义,由三个额外的项目扩展,并在本教程中进行了解释。

Instant

The Instant class represents a moment on the timeline in UTC.

Instant类表示UTC时间轴上的一个时刻。

The java.time framework has a resolution of nanoseconds, or 9 digits of a fractional second. Milliseconds is only 3 digits of a fractional second. Because millisecond resolution is common, java.time includes a handy factory method.

java。时间框架的分辨率为纳秒,或9位数的几分之一秒。毫秒仅仅是三位数的几分之一秒。因为毫秒级的分辨率很常见,java。时间包括一个方便的工厂方法。

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

millisecondsSinceEpoch: 1446959825213 is instant: 2015-11-08T05:17:05.213Z

毫秒:1446959825213 is instant: 2015-11-08t05:05:05.213

ZonedDateTime

To consider current week and current month, we need to apply a particular time zone.

要考虑当前周和当前月,我们需要应用一个特定的时区。

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

In zoneId: America/Montreal that is: 2015-11-08T00:17:05.213-05:00[America/Montreal]

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

Half-Open

In date-time work, we commonly use the Half-Open approach to defining a span of time. The beginning is inclusive while the ending in exclusive. Rather than try to determine the last split-second of the end of the week (or month), we get the first moment of the following week (or month). So a week runs from the first moment of Monday and goes up to but not including the first moment of the following Monday.

在日期-时间工作中,我们通常使用半开放的方法来定义时间跨度。开头是包容的,结尾是排他性的。与其试图确定一周(或一个月)的最后一秒,不如选择下一周(或下个月)的第一个时刻。一周从周一的第一个时刻开始,一直持续到下周一的第一个时刻。

Let's the first day of the week, and last. The java.time framework includes a tool for that, the with method and the ChronoField enum.

让我们从一周的第一天开始,到最后一天。java。时间框架包括一个工具,与方法和时域枚举。

By default, java.time uses the ISO 8601 standard. So Monday is the first day of the week (1) and Sunday is last (7).

默认情况下,java。time使用ISO 8601标准。所以星期一是一周的第一天,星期天是最后一天。

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

That week runs from: 2015-11-02T00:17:05.213-05:00[America/Montreal] to 2015-11-09T00:17:05.213-05:00[America/Montreal]

那个星期从:2015-11-02T00:17:05.213-05:00[美国/蒙特利尔]到2015-11-09T00:17:05.213-05:00[美国/蒙特利尔]

Oops! Look at the time-of-day on those values. We want the first moment of the day. The first moment of the day is not always 00:00:00.000 because of Daylight Saving Time (DST) or other anomalies. So we should let java.time make the adjustment on our behalf. To do that, we must go through the LocalDate class.

哦!看看这些值的时间。我们想要一天中的第一个时刻。由于夏令时(DST)或其他异常情况,一天中的第一个时刻并不总是00:00. 00.000。所以我们应该让java。是时候代表我们做出调整了。为此,我们必须遍历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 );

That week runs from: 2015-11-02T00:00-05:00[America/Montreal] to 2015-11-09T00:00-05:00[America/Montreal]

这周的时间是:2015-11-02T00:00-05:00[美国/蒙特利尔]到2015-11-09T00:00-05:00[美国/蒙特利尔]

And same for the month.

这个月也一样。

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

That month runs from: 2015-11-01T00:00-04:00[America/Montreal] to 2015-12-01T00:00-05:00[America/Montreal]

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

YearMonth

Another way to see if a pair of moments are in the same month is to check for the same YearMonth value.

另一种查看两个时刻是否在同一个月的方法是检查相同年份的月值。

For example, assuming thisZdt and thatZdt are both ZonedDateTime objects:

例如,假设thisZdt和thatZdt都是ZonedDateTime对象:

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

Milliseconds

I strongly recommend against doing your date-time work in milliseconds-from-epoch. That is indeed the way date-time classes tend to work internally, but we have the classes for a reason. Handling a count-from-epoch is clumsy as the values are not intelligible by humans so debugging and logging is difficult and error-prone. And, as we've already seen, different resolutions may be in play; old Java classes and Joda-Time library use milliseconds, while databases like Postgres use microseconds, and now java.time uses nanoseconds.

我强烈建议你不要在距离日期毫秒的时间段内工作。这确实是日期-时间类在内部工作的方式,但是我们有这些类是有原因的。处理一个count-from-epoch的操作是很笨拙的,因为这些值是人类无法理解的,所以调试和日志记录是困难且容易出错的。正如我们已经看到的,不同的决议可能在起作用;旧的Java类和Joda-Time库使用毫秒,而像Postgres这样的数据库使用微秒,现在使用Java。使用纳秒的时间。

Would you handle text as bits, or do you let classes such as String, StringBuffer, and StringBuilder handle such details?

您是将文本作为位来处理,还是让字符串、StringBuffer和StringBuilder等类来处理这些细节?

But if you insist, from a ZonedDateTime get an Instant, and from that get a milliseconds-count-from-epoch. But keep in mind this call can mean loss of data. Any microseconds or nanoseconds that you might have in your ZonedDateTime/Instant will be truncated (lost).

但是如果你坚持的话,从ZonedDateTime得到一个瞬间,然后从中得到一个毫秒级的值。但请记住,这个调用可能意味着数据丢失。ZonedDateTime/Instant中的任何微秒或纳秒都将被截断(丢失)。

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

#5


2  

To get the first day of the month, simply get a Date and set the current day to day 1 of the month. Clear hour, minute, second and milliseconds if you need it.

要得到一个月的第一天,只需得到一个日期,并将当前的日期设置为每月的第一天。如果你需要的话,清理小时、分钟、秒和毫秒。

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

First day of the week is the same thing, but using Calendar.DAY_OF_WEEK instead

一周的第一天是一样的,但是使用日历。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();
}

#6


1  

In this case:

在这种情况下:

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

So the Calendar.HOUR_OF_DAY returns 8, 9, 12, 15, 18 as the current running hour. I think will be better change such line by:

因此,日历。HOUR_OF_DAY返回8,9,12,15,18作为当前运行小时。我想最好把这条线改为:

c.set(Calendar.HOUR_OF_DAY,0);

this way the day always begin at 0 hour

这样一天总是从0点开始

#7


0  

You should be able to convert your number to a Java Calendar, e.g.:

你应该能够把你的号码转换成Java日历,例如:

 Calendar.getInstance().setTimeInMillis(myDate);

From there, the comparison shouldn't be too hard.

从这一点来看,这种比较应该不会太难。

#8


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

#9


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


    }

}

#10


0  

I have created some methods for this:

我为此创造了一些方法:

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

You can see more here.

你可以在这里看到更多。

#11


0  

Get First date of next month:-

下个月的第一次约会:-。

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

#12


-3  

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