오늘 자정과 내일 자정의 Java Date 객체를 만드는 방법은 무엇입니까?
내 코드에서 오늘 일어난 모든 일을 찾아야합니다. 따라서 오늘 00:00 am (오늘 아침 자정)부터 12:00 pm (오늘 자정)까지의 날짜와 비교해야합니다.
알아 ...
Date today = new Date();
... 지금 당장. 그리고 ...
Date beginning = new Date(0);
... 1970 년 1 월 1 일에 제로 타임을 얻습니다. 그러나 오늘 제로 시간과 제로 시간을 얻는 쉬운 방법은 무엇입니까?
최신 정보; 나는 이것을했지만 분명히 더 쉬운 방법이 있습니까?
Calendar calStart = new GregorianCalendar();
calStart.setTime(new Date());
calStart.set(Calendar.HOUR_OF_DAY, 0);
calStart.set(Calendar.MINUTE, 0);
calStart.set(Calendar.SECOND, 0);
calStart.set(Calendar.MILLISECOND, 0);
Date midnightYesterday = calStart.getTime();
Calendar calEnd = new GregorianCalendar();
calEnd.setTime(new Date());
calEnd.set(Calendar.DAY_OF_YEAR, calEnd.get(Calendar.DAY_OF_YEAR)+1);
calEnd.set(Calendar.HOUR_OF_DAY, 0);
calEnd.set(Calendar.MINUTE, 0);
calEnd.set(Calendar.SECOND, 0);
calEnd.set(Calendar.MILLISECOND, 0);
Date midnightTonight = calEnd.getTime();
java.util.Calendar
// today
Calendar date = new GregorianCalendar();
// reset hour, minutes, seconds and millis
date.set(Calendar.HOUR_OF_DAY, 0);
date.set(Calendar.MINUTE, 0);
date.set(Calendar.SECOND, 0);
date.set(Calendar.MILLISECOND, 0);
// next day
date.add(Calendar.DAY_OF_MONTH, 1);
JDK 8-java.time.LocalTime 및 java.time.LocalDate
LocalTime midnight = LocalTime.MIDNIGHT;
LocalDate today = LocalDate.now(ZoneId.of("Europe/Berlin"));
LocalDateTime todayMidnight = LocalDateTime.of(today, midnight);
LocalDateTime tomorrowMidnight = todayMidnight.plusDays(1);
조다 타임
JDK <8을 사용하는 경우 API가 정말 좋기 때문에 Joda Time을 권장합니다 .
DateTime date = new DateTime().toDateMidnight().toDateTime();
DateTime tomorrow = date.plusDays(1);
Joda Time 2.3 버전 DateMidnight
은 더 이상 사용되지 않으므로 다음을 사용하십시오.
DateTime today = new DateTime().withTimeAtStartOfDay();
DateTime tomorrow = today.plusDays(1).withTimeAtStartOfDay();
JVM의 현재 기본 시간대를 원하지 않으면 시간대를 전달하십시오.
DateTimeZone timeZone = DateTimeZone.forID("America/Montreal");
DateTime today = new DateTime(timeZone).withTimeAtStartOfDay(); // Pass time zone to constructor.
자정을 찾는 가장 쉬운 방법 :
Long time = new Date().getTime();
Date date = new Date(time - time % (24 * 60 * 60 * 1000));
다음날:
Date date = new Date(date.getTime() + 24 * 60 * 60 * 1000);
완전성을 위해 Java 8 을 사용하는 truncatedTo
경우 Instant
클래스 의 메소드를 사용하여 UTC 자정을 얻을 수도 있습니다 .
Instant.now().truncatedTo(ChronoUnit.DAYS);
Javadoc에 작성된
예를 들어, MINUTES 단위로 자르면 가장 가까운 분으로 반올림하여 초와 나노초를 0으로 설정합니다.
도움이 되길 바랍니다.
기억, Date
표현하는 데 사용되지 않습니다 날짜를 (!). 날짜를 나타내려면 달력이 필요합니다. 이:
Calendar c = new GregorianCalendar();
Calendar
현재 시간대의 현재 날짜를 나타내는 인스턴스 를 만듭니다 . 이제 필요한 것은로 설정하여 하루 (시, 분, 초 및 밀리 초) 아래의 모든 필드를 잘라내는 것 0
입니다. 오늘 자정이되었습니다.
이제 다음 날 자정을 얻으려면 하루를 추가해야합니다.
c.add(Calendar.DAY_OF_MONTH, 1);
86400
그 동안 발생할 수있는 여름 시간으로 인해 초 또는 24 시간 을 추가하는 것은 올바르지 않습니다.
업데이트 : 그러나이 문제를 처리하는 가장 좋아하는 방법 은 Commons Lang의 DateUtils 클래스 를 사용하는 것입니다 .
Date start = DateUtils.truncate(new Date(), Calendar.DAY_OF_MONTH))
Date end = DateUtils.addDays(start, 1);
그것은 Calendar
무대 뒤에서 사용 합니다 ...
이 방법들이 도움이 될 것입니다.
public static Date getStartOfDay(Date date) {
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
calendar.set(Calendar.HOUR_OF_DAY, 0);
calendar.set(Calendar.MINUTE, 0);
calendar.set(Calendar.SECOND, 0);
calendar.set(Calendar.MILLISECOND, 0);
return calendar.getTime();
}
과
public static Date getEndOfDay(Date date) {
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
calendar.set(Calendar.HOUR_OF_DAY, 23);
calendar.set(Calendar.MINUTE, 59);
calendar.set(Calendar.SECOND, 59);
calendar.set(Calendar.MILLISECOND, 999);
return calendar.getTime();
}
JodaTime 2.3부터는 toDateMidnight()
더 이상 사용되지 않습니다.
2.2 이후의 지원 중단 ---------------------- -DateMidnight [# 41] 이 수업은 개념에 결함이 있습니다 일부 시간대에서는 자정 시간이 가끔 발생하지 않습니다. 이는 일광 절약 시간 제로 00:00부터 01:00까지입니다. DateMidnight는 기본적으로 자정에 시간이 고정 된 DateTime입니다. LocalDate를 고려할 때 이러한 개념은 일반적으로 사용하기에 좋지 않은 개념입니다. DateMidnight를 LocalDate로 교체 또는 withTimeAtStartOfDay () 메소드를 사용하여 DateTime으로 바꾸십시오.
다음은 toDateMidnight()
메소드 가없는 샘플 코드 입니다.
암호
DateTime todayAtMidnight = new DateTime().withTimeAtStartOfDay();
System.out.println(todayAtMidnight.toString("yyyy-MM-dd HH:mm:ss"));
출력 ( 현지 시간대에 따라 다를 수 있음 )
2013-09-28 00:00:00
java.time
Java 8 이상을 사용하는 경우 java.time 패키지 ( Tutorial )를 사용해 볼 수 있습니다 .
LocalDate tomorrow = LocalDate.now().plusDays(1);
Date endDate = Date.from(tomorrow.atStartOfDay(ZoneId.systemDefault()).toInstant());
다른 답변, 특히 arganzheng 의 java.time 답변이 정확 합니다. 일부 언급했듯이, 오래된 java.util.Date/.Calendar 클래스는 잘못 설계되고 혼란스럽고 번거롭기 때문에 피해야합니다. 그것들은 java.time 클래스에 의해 대체되었습니다.
Let me add notes about strategy around handling midnight and spans of time.
Half-Open
In date-time work, spans of time are often defined using the “Half-Open” approach. In this approach the beginning is inclusive while the ending is exclusive. This solves problems and if used consistently makes reasoning about your date-time handling much easier.
One problem solved is defining the end of the day. Is the last moment of the day 23:59:59.999
(milliseconds)? Perhaps, in the java.util.Date class (from earliest Java; troublesome – avoid this class!) and in the highly successful Joda-Time library. But in other software, such as database like Postgres, the last moment will be 23:59:59.999999
(microseconds). But in other software such as the java.time framework (built into Java 8 and later, successor to Joda-Time) and in some database such the H2 Database, the last moment might be 23:59.59.999999999
(nanoseconds). Rather than splitting hairs, think in terms of first moment only, not last moment.
In Half-Open, a day runs from the first moment of one day and goes up to but does not include the first moment of the following day. So rather than think like this:
…from today at 00:00am (midnight early this morning) to 12:00pm (midnight tonight).
…think like this…
from first moment of today running up to but not including first moment of tomorrow:
( >=00:00:00.0
today AND <00:00:00.0
tomorrow )
In database work, this approach means not using the BETWEEN
operator in SQL.
Start of day
Furthermore, the first moment of the day is not always the time-of-day 00:00:00.0
. Daylight Saving Time (DST) in some time zones, and possibly other anomalies, can mean a different time starts the day.
So let the java.time classes do the work of determining the start of a day with a call to LocalDate::atStartOfDay( ZoneId )
. So we have to detour through LocalDate
and back to ZonedDateTime
as you can see in this example code.
ZoneId zoneId = ZoneId.of( "America/Montreal" );
ZonedDateTime now = ZonedDateTime.now( zoneId );
ZonedDateTime todayStart = now.toLocalDate().atStartOfDay( zoneId );
ZonedDateTime tomorrowStart = todayStart.plusDays( 1 );
Note the passing of the optional ZoneId
. If omitted your JVM’s current default time zone is applied implicitly. Better to be explicit.
Time zone is crucial to date-time work. The Question and some other Answers are potentially flawed because the do not consciously handle time zone.
Convert
If you must use a java.util.Date or .Calendar, look for new conversion methods added to those old classes.
java.util.Date utilDate = java.util.Date.from( todayStart.toInstant() );
java.util.GregorianCalendar gregCal = java.util.GregorianCalendar.from( todayStart );
Span of time
By the way, if you are doing much work with spans of time take a look at:
Duration
Period
Interval
TheInterval
class is found in the ThreeTen-Extra project, an extension to the java.time framework. This project is the proving ground for possible future additions to java.time.Interval todayMontreal = Interval.of( todayStart.toInstant() , tomorrowStart.toInstant() );
About java.time
The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date
, Calendar
, & SimpleDateFormat
.
The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.
To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.
You may exchange java.time objects directly with your database. Use a JDBC driver compliant with JDBC 4.2 or later. No need for strings, no need for java.sql.*
classes.
Where to obtain the java.time classes?
- Java SE 8, Java SE 9, Java SE 10, Java SE 11, and later - Part of the standard Java API with a bundled implementation.
- Java 9 adds some minor features and fixes.
- Java SE 6 and Java SE 7
- Most 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 ThreeTenABP project adapts ThreeTen-Backport (mentioned above). See How to use ThreeTenABP….
The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval
, YearWeek
, YearQuarter
, and more.
This appears to be an option:
DateFormat justDay = new SimpleDateFormat("yyyyMMdd");
Date thisMorningMidnight = justDay.parse(justDay.format(new Date()));
to add a day to it, either
Date tomorrow = new Date(thisMorningMidnight.getTime() + 24 * 60 * 60 * 1000);
or
Calendar c = Calendar.getInstance();
c.setTime(thisMorningMidnight);
c.add(Calendar.DATE, 1);
Date tomorrowFromCalendar = c.getTime();
I have a hunch the latter is preferred in case of something weird like daylight savings causing adding 24 hours to not be enough (see https://stackoverflow.com/a/4336131/32453 and its other answers).
I did this differently than everyone else here did. I'm new to Java, so maybe my solution is poor.
Date now = new Date();
Date midnightToday = new Date(now.getYear(), now.getMonth(), now.getDate());
I'm not sure this works yet, but either way, I'd appreciate any feedback on this solution.
I'm confused by the statement above that you can calculate tomorrow by calling:
c.add(Calendar.DAY_OF_MONTH, 1);
If you add 1 to the day of the month and it's the 31st day, don't you get the 32nd day of the month?
Why are times/dates not all based on UTC in Java? I would think Timezones should only be needed when used with i/o, but internally should always be used in UTC. However, the classes seem to include Timezone info which seems not only wasteful, but prone to coding errors.
Because of one day is 24 * 60 * 60 * 1000
ms, the midnight of this day can be calculate as...
long now = System.currentTimeMillis();
long delta = now % 24 * 60 * 60 * 1000;
long midnight = now - delta;
Date midnightDate = new Date(midnight);`
Pretty much as the answers before, but nobody mentioned AM_PM parameter:
Calendar cal = Calendar.getInstance();
cal.set(Calendar.HOUR, 0);
cal.set(Calendar.MINUTE, 0);
cal.set(Calendar.SECOND, 0);
cal.set(Calendar.MILLISECOND, 0);
cal.set(Calendar.AM_PM, Calendar.AM);
Apache Commons Lang
DateUtils.isSameDay(date1, date2)
http://commons.apache.org/proper/commons-lang/javadocs/api-2.6/org/apache/commons/lang/time/DateUtils.html#isSameDay(java.util.Date, java.util.Date)
The simplest way with JodaTime
DateMidnight date = DateMidnight.now();
Date now= new Date();
// Today midnight
Date todayMidnight = new Date(endTime.getTime() -endTime.getTime()%DateUtils.MILLIS_PER_DAY);
// tomorrow midnight
Date tomorrowMidnight = new Date(endTime.getTime() -endTime.getTime()%DateUtils.MILLIS_PER_DAY + DateUtils.MILLIS_PER_DAY);
Using apache commons..
//For midnight today
Date today = new Date();
DateUtils.truncate(today, Calendar.DATE);
//For midnight tomorrow
Date tomorrow = DateUtils.addDays(today, 1);
DateUtils.truncate(tomorrow, Calendar.DATE);
I know this is very old post. I thought to share my knowledge here !
For the date Mid night today with exact Time zone you can use following
public static Date getCurrentDateWithMidnightTS(){
return new Date(System.currentTimeMillis() - (System.currentTimeMillis()%(1000*60*60*24)) - (1000*60 * 330));
}
Where (1000*60 * 330)
is being subtracted i.e. actually related to time zone for example Indian time zone i.e. kolkata differs +5:30hrs from actual . So subtracting that with converting into milliseconds.
So change last substracted number according to you. I m creating a product i.e. only based in India So just used specific timestamp.
Date todayMidnightUTC = java.sql.Date.valueOf(LocalDate.now());
Date tomorrowMidnightUTC = java.sql.Date.valueOf(LocalDate.now().plusDays(1));
Date anyMidnightLocal = java.sql.Date.valueOf(LocalDate.from(dateTime.toInstant().atZone(ZoneId.systemDefault())));
But beware that java.sql.Date.toInstant()
always throws UnsupportedOperationException
.
Via LocalDate to java.util.Date and vice versa simpliest conversion?
Old fashioned way..
private static Date getDateWithMidnight(){
long dateInMillis = new Date().getTime();
return new Date(dateInMillis - dateInMillis%(1000*60*60*24) - TimeZone.getDefault().getOffset(dateInMillis));
}
'IT' 카테고리의 다른 글
MVC의 비즈니스 로직 (0) | 2020.05.25 |
---|---|
Java SDK를 설치 한 후 Linux에서 어디서 찾을 수 있습니까? (0) | 2020.05.25 |
NVIDIA NVML 드라이버 / 라이브러리 버전 불일치 (0) | 2020.05.25 |
Java가 파일 이름과 이름이 다른 클래스를 컴파일 할 수있는 이유는 무엇입니까? (0) | 2020.05.25 |
Oracle SQL에서 세미콜론과 슬래시를 언제 사용해야합니까? (0) | 2020.05.25 |