Java 用今天的日期检查日期
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6537535/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Check date with todays date
提问by Zaask
I have written some code to check two dates, a start date and an end date. If the end date is before the start date, it will give a prompt that says the end date is before start date.
我编写了一些代码来检查两个日期,一个开始日期和一个结束日期。如果结束日期早于开始日期,则会提示结束日期早于开始日期。
I also want to add a check for if the start date is before today (today as in the day of which the user uses the application) How would I do this? ( Date checker code below, also all this is written for android if that has any bearing)
我还想检查开始日期是否在今天之前(今天与用户使用应用程序的日期一样)我将如何执行此操作?(下面的日期检查器代码,如果有任何意义,所有这些都是为android编写的)
if (startYear > endYear) {
fill = fill + 1;
message = message + "End Date is Before Start Date" + "\n";
} else if (startMonth > endMonth && startYear >= endYear) {
fill = fill + 1;
message = message + "End Date is Before Start Date" + "\n";
} else if (startDay > endDay && startMonth >= endMonth && startYear >= endYear) {
fill = fill + 1;
message = message + "End Date is Before Start Date" + "\n";
}
采纳答案by sudocode
Does this help?
这有帮助吗?
Calendar c = Calendar.getInstance();
// set the calendar to start of today
c.set(Calendar.HOUR_OF_DAY, 0);
c.set(Calendar.MINUTE, 0);
c.set(Calendar.SECOND, 0);
c.set(Calendar.MILLISECOND, 0);
// and get that as a Date
Date today = c.getTime();
// or as a timestamp in milliseconds
long todayInMillis = c.getTimeInMillis();
// user-specified date which you are testing
// let's say the components come from a form or something
int year = 2011;
int month = 5;
int dayOfMonth = 20;
// reuse the calendar to set user specified date
c.set(Calendar.YEAR, year);
c.set(Calendar.MONTH, month);
c.set(Calendar.DAY_OF_MONTH, dayOfMonth);
// and get that as a Date
Date dateSpecified = c.getTime();
// test your condition
if (dateSpecified.before(today)) {
System.err.println("Date specified [" + dateSpecified + "] is before today [" + today + "]");
} else {
System.err.println("Date specified [" + dateSpecified + "] is NOT before today [" + today + "]");
}
回答by Mitch Salopek
I assume you are using integers to represent your year, month, and day? If you want to remain consistent, use the Date methods.
我假设您使用整数来表示您的年、月和日?如果要保持一致,请使用 Date 方法。
Calendar cal = new Calendar();
int currentYear, currentMonth, currentDay;
currentYear = cal.get(Calendar.YEAR);
currentMonth = cal.get(Calendar.MONTH);
currentDay = cal.get(Calendar.DAY_OF_WEEK);
?if(startYear < currentYear)
? ? ? ? ? ? {
? ? ? ? ? ? ? ? message = message + "Start Date is Before Today" + "\n";
? ? ? ? ? ? }
? ? ? ? else if(startMonth < currentMonth && startYear <= currentYear)
? ? ? ? ? ? ? ? {
? ? ? ? ? ? ? ? ? ? message = message + "Start Date is Before Today" + "\n";
? ? ? ? ? ? ? ? }
? ? ? ? else if(startDay < currentDay && startMonth <= currentMonth && startYear <= currentYear)
? ? ? ? ? ? ? ? ? ? {
? ? ? ? ? ? ? ? ? ? ? ? message = message + "Start Date is Before Today" + "\n";
? ? ? ? ? ? ? ? ? ? }
回答by martin
回答by Milan Shukla
to check if a date is today's date or not only check for dates not time included with that so make time 00:00:00 and use the code below
检查日期是否是今天的日期,或者不仅检查日期而不是包含在其中的时间,因此将时间设为 00:00:00 并使用下面的代码
Calendar c = Calendar.getInstance();
// set the calendar to start of today
c.set(Calendar.HOUR_OF_DAY, 0);
c.set(Calendar.MINUTE, 0);
c.set(Calendar.SECOND, 0);
c.set(Calendar.MILLISECOND, 0);
Date today = c.getTime();
// or as a timestamp in milliseconds
long todayInMillis = c.getTimeInMillis();
int dayOfMonth = 24;
int month = 4;
int year =2013;
// reuse the calendar to set user specified date
c.set(Calendar.YEAR, year);
c.set(Calendar.MONTH, month - 1);
c.set(Calendar.DAY_OF_MONTH, dayOfMonth);
c.set(Calendar.HOUR_OF_DAY, 0);
c.set(Calendar.MINUTE, 0);
c.set(Calendar.SECOND, 0);
c.set(Calendar.MILLISECOND, 0);
// and get that as a Date
Date dateSpecified = c.getTime();
// test your condition
if (dateSpecified.before(today)) {
Log.v(" date is previou")
} else if (dateSpecified.equal(today)) {
Log.v(" date is today ")
}
else if (dateSpecified.after(today)) {
Log.v(" date is future date ")
}
Hope it will help....
希望它会有所帮助......
回答by Vladimir.Shramov
boolean isBeforeToday(Date d) {
Date today = new Date();
today.setHours(0);
today.setMinutes(0);
today.setSeconds(0);
return d.before(today);
}
回答by Kishath
Don't complicate it that much. Use this easy way. Import DateUtils java class and call the following methods which returns a boolean.
不要把它复杂化。使用这个简单的方法。导入 DateUtils java 类并调用以下返回布尔值的方法。
DateUtils.isSameDay(date1,date2);
DateUtils.isSameDay(calender1,calender2);
DateUtils.isToday(date1);
For more info refer this article DateUtils Java
有关更多信息,请参阅本文DateUtils Java
回答by carlol
another way to do this operation:
执行此操作的另一种方法:
public class TimeUtils {
/**
* @param timestamp
* @return
*/
public static boolean isToday(long timestamp) {
Calendar now = Calendar.getInstance();
Calendar timeToCheck = Calendar.getInstance();
timeToCheck.setTimeInMillis(timestamp);
return (now.get(Calendar.YEAR) == timeToCheck.get(Calendar.YEAR)
&& now.get(Calendar.DAY_OF_YEAR) == timeToCheck.get(Calendar.DAY_OF_YEAR));
}
}
回答by Spektakulatius
Try this:
尝试这个:
public static boolean isToday(Date date)
{
return org.apache.commons.lang3.time.DateUtils.isSameDay(Calendar.getInstance().getTime(),date);
}
回答by Basil Bourque
The other answers ignore the crucial issue of time zone.
其他答案忽略了时区的关键问题。
The other answers use outmoded classes.
其他答案使用过时的课程。
Avoid old date-time classes
避免旧的日期时间课程
The old date-time classes bundled with the earliest versions of Java are poorly designed, confusing, and troublesome. Avoid java.util.Date/.Calendar and related classes.
与最早版本的 Java 捆绑在一起的旧日期时间类设计不佳、令人困惑且麻烦。避免 java.util.Date/.Calendar 和相关类。
java.time
时间
- In Java 8 and later use the built-in java.timeframework. See Tutorial.
- In Java 7 or 6, add the backport of java.timeto your project.
- In Android, use the wrapped version of that backport.
- 在 Java 8 及更高版本中使用内置的java.time框架。请参阅教程。
- 在 Java 7 或 6 中,将java.time的backport添加到您的项目中。
- 在Android 中,使用该backport的包装版本。
LocalDate
LocalDate
For date-only values, without time-of-day and without time zone, use the LocalDate
class.
对于没有时间和时区的仅日期值,请使用LocalDate
该类。
LocalDate start = LocalDate.of( 2016 , 1 , 1 );
LocalDate stop = start.plusWeeks( 1 );
Time Zone
时区
Be aware that while LocalDate
does not storea time zone, determininga date such as “today” requires a time zone. For any given moment, the date may vary around the world by time zone. For example, a new day dawns earlier in Paris than in Montréal. A moment after midnight in Paris is still “yesterday” in Montréal.
请注意,虽然LocalDate
不存储时区,但确定“今天”等日期需要时区。对于任何给定时刻,日期可能因时区而异。例如,新的一天在巴黎比在蒙特利尔早。巴黎午夜过后的一刻在蒙特利尔仍然是“昨天”。
If all you have is an offset-from-UTC, use ZoneOffset
. If you have a full time zone (continent/region), then use ZoneId
. If you want UTC, use the handy constant ZoneOffset.UTC
.
如果您只有一个offset-from-UTC,请使用ZoneOffset
. 如果您有完整的时区(大陆/地区),则使用ZoneId
. 如果您想要 UTC,请使用方便的常量ZoneOffset.UTC
。
ZoneId zoneId = ZoneId.of( "America/Montreal" );
LocalDate today = LocalDate.now( zoneId );
Comparing is easy with isEqual
, isBefore
, and isAfter
methods.
比较容易用isEqual
,isBefore
和isAfter
方法。
boolean invalidInterval = stop.isBefore( start );
We can check to see if today is contained within this date range. In my logic shown here I use the Half-Openapproach where the beginning is inclusivewhile the ending is exclusive. This approach is common in date-time work. So, for example, a week runs from a Monday going up to but not including the following Monday.
我们可以检查今天是否包含在这个日期范围内。在此处显示的逻辑中,我使用半开方法,其中开头是包容性的,而结尾是独占性的。这种方法在日期时间工作中很常见。因此,例如,一周从星期一开始直到但不包括下一个星期一。
// Is today equal or after start (not before) AND today is before stop.
boolean intervalContainsToday = ( ! today.isBefore( start ) ) && today.isBefore( stop ) ) ;
Interval
Interval
If working extensively with such spans of time, consider adding the ThreeTen-Extralibrary to your project. This library extends the java.time framework, and is the proving ground for possible additions to java.time.
如果在如此长的时间内广泛工作,请考虑将ThreeTen-Extra库添加到您的项目中。该库扩展了 java.time 框架,并且是对 java.time 进行可能添加的试验场。
ThreeTen-Extra includes an Interval
class with handy methods such as abuts
, contains
, encloses
, overlaps
, and so on.
ThreeTen-Extra 包含一个Interval
带有方便方法的类,例如abuts
、contains
、encloses
、overlaps
等。
About java.time
关于java.time
The java.timeframework is built into Java 8 and later. These classes supplant the troublesome old legacydate-time classes such as java.util.Date
, Calendar
, & SimpleDateFormat
.
该java.time框架是建立在Java 8和更高版本。这些类取代了麻烦的旧的遗留日期时间类,例如java.util.Date
, Calendar
, & SimpleDateFormat
。
The Joda-Timeproject, now in maintenance mode, advises migration to the java.timeclasses.
现在处于维护模式的Joda-Time项目建议迁移到java.time类。
To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.
要了解更多信息,请参阅Oracle 教程。并在 Stack Overflow 上搜索许多示例和解释。规范是JSR 310。
You may exchange java.timeobjects directly with your database. Use a JDBC drivercompliant with JDBC 4.2or later. No need for strings, no need for java.sql.*
classes.
您可以直接与您的数据库交换java.time对象。使用符合JDBC 4.2或更高版本的JDBC 驱动程序。不需要字符串,不需要类。java.sql.*
Where to obtain the java.time classes?
从哪里获得 java.time 类?
- Java SE 8, Java SE 9, Java SE 10, and later
- Built-in.
- Part of the standard Java API with a bundled implementation.
- Java 9 adds some minor features and fixes.
- Java SE 6and Java SE 7
- Much of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport.
- Android
- Later versions of Android bundle implementations of the java.time classes.
- For earlier Android (<26), the ThreeTenABPproject adapts ThreeTen-Backport(mentioned above). See How to use ThreeTenABP….
- Java SE 8、Java SE 9、Java SE 10及更高版本
- 内置。
- 具有捆绑实现的标准 Java API 的一部分。
- Java 9 添加了一些小功能和修复。
- Java SE 6和Java SE 7
- 多的java.time功能后移植到Java 6和7在ThreeTen-反向移植。
- 安卓
- java.time 类的更高版本的 Android 捆绑实现。
- 对于早期的 Android(<26),ThreeTenABP项目采用了ThreeTen-Backport(上面提到过)。请参阅如何使用ThreeTenABP ...。
回答by makata
Android already has a dedicated class for this. Check DateUtils.isToday(long when)
Android 已经为此提供了一个专门的类。检查DateUtils.isToday(long when)