我有几个事件的日期,以毫秒[1]表示,我想知道哪些事件在当前周和本月内,但是我不知道如何获取第一天(天/月/年) ),并将其转换为毫秒,与该月的第一天相同。
[1]Since January 1, 1970, 00:00:00 GMT
我有几个事件的日期,以毫秒[1]表示,我想知道哪些事件在当前周和本月内,但是我不知道如何获取第一天(天/月/年) ),并将其转换为毫秒,与该月的第一天相同。
[1]Since January 1, 1970, 00:00:00 GMT
Answers:
本周(以毫秒为单位):
// 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());
cal.clear(Calendar.HOUR_OF_DAY);
与cal.set(Calendar.HOUR_OF_DAY, 0);
类似指示在日历的javadoc的。
可以借助以下方法确定一周的第一天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();
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
值。
例如,假设thisZdt
和thatZdt
都是ZonedDateTime
对象:
boolean inSameMonth = YearMonth.from( thisZdt ).equals( YearMonth.from( thatZdt ) ) ;
我强烈建议您不要以毫秒为单位进行日期时间工作。这确实是日期时间类倾向于在内部工作的方式,但是我们之所以有这些类是有原因的。由于人们无法理解这些值,因此很难计算时间,因此调试和记录非常困难且容易出错。而且,正如我们已经看到的,不同的分辨率可能会起作用。旧的Java类和Joda-Time库使用毫秒,而Postgres之类的数据库使用毫秒,而现在的java.time使用纳秒。
你会处理文本作为位,还是你让类,如String
,StringBuffer
和StringBuilder
处理这样的细节?
但是,如果您坚持要求,则从ZonedDateTime
获得Instant
,然后从那个获得毫秒数。但是请记住,此调用可能意味着数据丢失。您ZonedDateTime
/中可能存在的任何微秒或纳秒都Instant
将被截断(丢失)。
long millis = firstOfWeek.toInstant().toEpochMilli(); // Possible data loss.
该java.time框架是建立在Java 8和更高版本。这些类取代麻烦的老传统日期时间类,如java.util.Date
,Calendar
,和SimpleDateFormat
。
要了解更多信息,请参见Oracle教程。并在Stack Overflow中搜索许多示例和说明。规格为JSR 310。
现在处于维护模式的Joda-Time项目建议迁移到java.time类。
您可以直接与数据库交换java.time对象。使用与JDBC 4.2或更高版本兼容的JDBC驱动程序。不需要字符串,不需要类。java.sql.*
在哪里获取java.time类?
注意!
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()) {...
要获取该月的第一天,只需获取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();
我为此创建了一些方法:
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());
}
你可以在这里看到更多。
您可以使用该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
ZonedDateTime
或OffsetDateTime
用于一个日期和时间需要以表示在时间轴上的固定点。(2)将一天的结束时间定义为第二天的第一时刻(不包括在内),将一天(并因此将周和月)定义为半开放时间间隔。这样做更正确(不排除一天中的最后一纳秒),有时还会提供更简单的代码。
在这种情况下:
// 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小时开始
获取下个月的第一个日期:-
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);
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()));
}
}
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);
}
}
在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
轻松转换为毫秒的任何想法?
Instant
使用它们的对象isBefore
,isEqual
或isAfter
方法。您从那里得到了短暂的收获Instant.ofEpochMilli(someMillisecondValue)
。是的,转换a的更简单方法LocalDateTime
是firstOfWeek.atZone(ZoneId.systemDefault()).toInstant()
。
我使用这个技巧来获取当前月份的第一天,注意顺序是星期二2为1,星期二3为星期一....依此类推
Calendar cal = new GregorianCalendar();
int startDay = cal.get(Calendar.DAY_OF_YEAR) % 7 + 1;
System.out.println(startDay);
java.util.Date
,java.util.Calendar
和java.text.SimpleDateFormat
现在的遗产,由取代java.time类。在ThreeTen-Backport项目中,大多数java.time功能都被反向移植到Java 6和Java 7 。在ThreeTenABP中进一步适用于早期的Android(<26)。请参阅如何使用ThreeTenABP…。
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;
}
java.util.Date
,java.util.Calendar
和java.text.SimpleTextFormat
现在的遗产,由取代java.time类。请参见Oracle教程。
1
...