program tip

Java 날짜 차단 시간 정보

radiobox 2020. 8. 2. 18:05
반응형

Java 날짜 차단 시간 정보


날짜 및 시간 정보가 포함 된 Java Date 객체가 있습니다. 시간 정보를 차단하고 시간-분-초를 자르는 방법을 작성하고 싶습니다. 날짜 만 남았습니다.

입력 예 :

2008-01-01 13:15:00

예상 출력 :

2008-01-01 00:00:00

팁이 있습니까? 나는 이런 식으로 시도했다 :

(timestamp / (24 * 60 * 60 * 1000)) * (24 * 60 * 60 * 1000)

그러나 시간대에 문제가 발생했습니다.


추천 날짜 / 시간 조작을 할 수있는 방법은 사용하는 Calendar개체를 :

Calendar cal = Calendar.getInstance(); // locale-specific
cal.setTime(dateObject);
cal.set(Calendar.HOUR_OF_DAY, 0);
cal.set(Calendar.MINUTE, 0);
cal.set(Calendar.SECOND, 0);
cal.set(Calendar.MILLISECOND, 0);
long time = cal.getTimeInMillis();

Apache Commons Lang DateUtils 자르기 메소드 를 살펴 보셨습니까 ?

Date truncatedDate = DateUtils.truncate(new Date(), Calendar.DATE);

시간 요소를 제거합니다.


Joda 를 보았 습니까? 날짜와 시간으로 작업 하는 것이 훨씬 쉽고 직관적 인 방법입니다. 예를 들어 LocalDateTimeLocalDate 객체 간에 사소한 변환이 가능 합니다.

예 : (API를 설명하기 위해)

LocalDate date = new LocalDateTime(milliseconds).toLocalDate()

또한 날짜 / 시간 포맷터의 일부 스레드 안전 문제를 해결하며 Java의 날짜 / 시간 문제를 처리하는 데 강력하게 권장됩니다.


이제 Java 8 이상에 내장 된 java.time 클래스 에 비추어 빠른 업데이트 만하면 됩니다.

LocalDateTimetruncatedTo여기서 말하는 내용을 효과적으로 처리 하는 방법이 있습니다.

LocalDateTime.now().truncatedTo(ChronoUnit.MINUTES)

현재 시간을 분 단위로 표시합니다.

2015-03-05T11:47

DAYS보다 작은 ChronoUnit(또는 TemporalUnit)를 사용 하여 잘림을 실행할 수 있습니다 (잘림은 날짜 부분이 아닌 LocalDateTime의 시간 부분에만 적용되므로).


Date date = new Date();
Calendar cal = Calendar.getInstance();
cal.setTime(date);
cal.set(Calendar.HOUR_OF_DAY, 0);
cal.set(Calendar.MINUTE, 0);
cal.set(Calendar.SECOND, 0);
cal.set(Calendar.MILLISECOND, 0);
date = cal.getTime();

Joda를 사용하면 쉽게 예상 날짜를 얻을 수 있습니다.

주석 작성자의 메모에 따르면 버전 2.7 (2.2 이전의 일부 버전 이후)에서 더 이상 toDateMidnight사용되지 않거나 적절하게 이름이 지정 withTimeAtStartOfDay()되어 편리합니다.

DateTime.now().withTimeAtStartOfDay()

가능한.

더 멋진 API가 추가되었습니다.

이전 버전으로 할 수있는 일

new DateTime(new Date()).toDateMidnight().toDate()

타임 스탬프의 경우 :

timestamp -= timestamp % (24 * 60 * 60 * 1000)

다음과 같이 잘림과 함께 Apache의 DateUtils를 사용하십시오.

DateUtils.truncate(Calendar.getInstance().getTime(), Calendar.DATE);

새로운 java8 API로 잘라 버렸습니다. 나는 한 가지 이상한 일에 직면했지만 일반적으로 잘립니다 ...

Instant instant = date.toInstant();
instant = instant.truncatedTo(ChronoUnit.DAYS);
date = Date.from(instant);

java.util.Date JavaDocs에서 :

Date 클래스는 밀리 초 단위로 특정 순간을 나타냅니다.

그리고 java.sql.Date JavaDocs에서 :

SQL DATE의 정의를 준수하려면 인스턴스가 연관된 특정 시간대에서 시간, 분, 초 및 밀리 초를 0으로 설정하여 java.sql.Date 인스턴스로 랩핑 된 밀리 초 값을 '정규화'해야합니다. .

따라서 가장 좋은 방법은 시간 부분이 필요하지 않은 경우 java.sql.Date를 사용하는 것입니다.

java.util.Date utilDate = new java.util.Date();
java.sql.Date sqlDate = new java.sql.Date(System.currentTimeMillis());

출력은 다음과 같습니다.

java.util.Date : Thu Apr 26 16:22:53 PST 2012
java.sql.Date  : 2012-04-26

tl; dr

LocalDateTime.parse(                            // Lacking an offset or time zone, parse as a `LocalDateTime`. *Not* a specific moment in time.
    "2008-01-01 13:15:00".replace( " " , "T" )  // Alter input string to comply with ISO 8601 standard format.
)
.toLocalDate()                                  // Extract a date-only value.
.atStartOfDay(                                  // Do not assume the day starts at 00:00:00. Let class determine start-of-day.
    ZoneId.of( "Europe/Paris" )                 // Determining a specific start-of-day requires a time zone.
)                                               // Result is a `ZonedDateTime` object. At this point we have a specific moment in time, a point on the timeline.
.toString()                                     // Generate a String in standard ISO 8601 format, wisely extended to append the name of the time zone in square brackets.

2008-01-01T00 : 00 + 01 : 00 [유럽 / 파리]

원하는 형식으로 문자열을 생성하려면 a를 전달하십시오 DateTimeFormatter.

LocalDateTime.parse(                            // Lacking an offset or time zone, parse as a `LocalDateTime`. *Not* a specific moment in time.
    "2008-01-01 13:15:00".replace( " " , "T" )  // Alter input string to comply with ISO 8601 standard format.
)
.toLocalDate()                                  // Extract a date-only value.
.atStartOfDay(                                  // Do not assume the day starts at 00:00:00. Let class determine start-of-day.
    ZoneId.of( "Europe/Paris" )                 // Determining a specific start-of-day requires a time zone.
)                                               // Result is a `ZonedDateTime` object. At this point we have a specific moment in time, a point on the timeline.
.format(                                        // Generate a String representing the object’s value.
    DateTimeFormatter.ISO_LOCAL_DATE_TIME       // Built-in predefined formatter close to what you want. 
)
.replace( "T" , " " )                           // Replace the standard’s use of a 'T' in the middle with your desired SPACE character.

2008-01-01 00:00:00

세부

다른 답변은 정확하지만 이제 java.time 프레임 워크에 의해 수정 된 이전 날짜-시간 클래스를 사용하십시오.

java.time

java.time 프레임 워크는 Java 8 이상에 내장되어 있습니다. 대부분의 java.time 기능은 Java 6 & 7 ( ThreeTen-Backport ) 로 백 포트 되고 Android ( ThreeTenABP )에 더 적합합니다 .

먼저 표준 버전의 ISO 8601 형식을 준수하도록 입력 문자열을 변경하십시오. 표준 ISO 8601 형식은 기본적으로 날짜-시간 값을 나타내는 문자열 구문 분석 / 생성에 java.time 클래스에서 사용됩니다. 중간에 해당 SPACE를로 교체해야합니다 T.

String input = "2008-01-01 13:15:00".replace( " " , "T" );  // → 2008-01-01T13:15:00

이제 LocalDateTime'로컬'은 특정 지역이 없음을 의미 하는로 해석 할 수 있습니다. 입력에 UTC로부터의 오프셋 또는 시간대 정보가 없습니다.

LocalDateTime ldt = LocalDateTime.parse( input );

ldt.toString ()… 2008-01-01T13 : 15 : 00

시간이나 시간대를 신경 쓰지 않으면로 변환하십시오 LocalDate.

LocalDate ld = ldt.toLocalDate();

ld.toString ()… 2008-01-01

오늘의 첫 순간

If instead you want the time-of-day set to the first moment of the day, use a ZonedDateTime class, then convert to a LocalDate object to call its atStartOfDay method. Be aware that the first moment may not be the time 00:00:00 because of Daylight Saving Time or perhaps other anomalies.

The time zone is crucial because for any given moment the date varies around the world by zone. For example, a few moments after midnight in Paris is a new day for Parisians but is still “yesterday” in Montréal for the Canadians.

ZoneId zoneId = ZoneId.of( "America/Montreal" );
ZonedDateTime zdt = ldt.atZone( zoneId );
LocalDate ldFromZdt = zdt.toLocalDate();
ZonedDateTime zdtStartOfDay = ldFromZdt.atStartOfDay( zoneId );

zdtStartOfDay.toString()… 2008-01-01T00:00:00-05:00[America/Montreal]

UTC

To see that moment through the lens of the UTC time zone, extract a Instant object. Both the ZonedDateTime and Instant will represent the same moment on the timeline but appear as two different wall-clock times.

An Instant is the basic building-block class in java.time, always in UTC by definition. Use this class frequently, as you should generally be doing your business logic, data storage, and data exchange in UTC.

Instant instant = zdtStartOfDay.toInstant();

instant.toString()… 2008-01-01T05:00:00Z

We see 5 AM rather than stroke-of-midnight. In standard format, the Z on the end is short for Zulu and means “UTC”.


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?

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.


Use the Calendar class's set() method to set the HOUR_OF_DAY, MINUTE, SECOND and MILLISECOND fields to zero.


The question is contradictory. It asks for a date without a time of day yet displays an example with a time of 00:00:00.

Joda-Time

UPDATE: The Joda-Time project is now in maintenance mode, with the team advising migration to the java.time classes. See my other Answer for java.time solution.

If instead you want the time-of-day set to the first moment of the day, use a DateTime object on the Joda-Time library and call its withTimeAtStartOfDay method. Be aware that the first moment may not be the time 00:00:00 because of Daylight Saving Time or perhaps other anomalies.


Just clear() redundant fields.

Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
calendar.set(Calendar.HOUR_OF_DAY, 0);
calendar.clear(Calendar.MINUTE);
calendar.clear(Calendar.SECOND);
calendar.clear(Calendar.MILLISECOND);
Date truncatedDate = calendar.getTime();

From Java 8 a better option is to use truncatedTo method of LocalDateTime, e.g.:

LocalDateTime.now().truncatedTo(ChronoUnit.DAYS)

It really annoyed me that the new "improved" calendar constructor doesn't take an int for milliseconds like the "awful" old Date one. I then got really cross and wrote this:

long stuffYou = startTime.getTimeInMillis() % 1000;
startTime.setTimeInMillis(startTime.getTimeInMillis() - stuffYou);

I didn't use the word "stuff" at the time, but then I discovered the happiness of this:

startTime.set(Calendar.MILLISECOND, 0);

But I'm still quite cross about it.


You can do this to avoid timezone issue:

public static Date truncDate(Date date) {
    Calendar cal = Calendar.getInstance(TimeZone.getTimeZone("UTC"));
    cal.setTime(date);
    cal.set(Calendar.HOUR_OF_DAY, 0);
    cal.set(Calendar.MINUTE, 0);
    cal.set(Calendar.SECOND, 0);
    cal.set(Calendar.MILLISECOND, 0);
    return cal.getTime();
}

Although Java Date object is timestamp value, but during truncate, it will be converted to local timezone, so you will get surprising value if you expect value from UTC timezone.


Might be a late response but here is a way to do it in one line without using any libraries:

new SimpleDateFormat("yyyy-MM-dd").parse(new SimpleDateFormat("yyyy-MM-dd").format(YOUR_TIMESTAMP))

With Joda-Time since version 2.0 you can use LocalDate.toDate().

Simply

// someDatetime is whatever java.util.Date you have.
Date someDay = new LocalDate(someDatetime).toDate();

For all the answers using Calendar, you should use it like this instead

public static Date truncateDate(Date date) {
    Calendar c = Calendar.getInstance();
    c.setTime(date);
    c.set(Calendar.HOUR_OF_DAY, c.getActualMinimum(Calendar.HOUR_OF_DAY));
    c.set(Calendar.MINUTE, c.getActualMinimum(Calendar.MINUTE));
    c.set(Calendar.SECOND, c.getActualMinimum(Calendar.SECOND));
    c.set(Calendar.MILLISECOND, c.getActualMinimum(Calendar.MILLISECOND));
    return c.getTime();
}

But I prefer this:

public static Date truncateDate(Date date) {
    return new java.sql.Date(date.getTime());
}

I fixed the issue like this(in Eastern eight zone(Beijing time)):

private Date getTruncatedDate(Date d) {
    if (d == null) {
        return null;
    }
    long h = 60 * 60 * 1000L;
    long dateStamp = d.getTime() - (d.getTime() + 8 * h) % (24 * h);
    return new Date(dateStamp);
}

First of all, you should be clear what is time stamp. Time stamp is the total milliseconds from Jan 01 00:00:00 1970 of GMT(same as UTC), or Thu Jan 01 08:00:00 CST 1970 to now.

Remember: Time stamp is independent of time zone.

So you get same result with the following statement in differnt time zones:

System.out.println(new Date().getTime());

And

System.out.println(new Date(0));

prints diferent time info in different time zones: If you set your pc time zone as UTC, you get

Thu Jan 01 00:00:00 UTC 1970

But if you set the time zone as (UTC +8:00) Beijing, Chongqing, HongKong, Urumq, you get:

Thu Jan 01 08:00:00 CST 1970

Java gets the time stamp, then displays date and time info according on the time zone.

For the introduction of how Java displays date and time info in different time zones, how to trancate the time info is easy. You should get the time stamp , and take the time zone into account when cut off the time info. Then you can create a new Date object with the cut time stamp(we can call it date stamp), java will compensate the time zone when displays date info.

As in Eastern eight zone(Beijing time), the Beijing time is earlier 8 hours than GMT, so you should subtract more 8 hours when you do the modulo operation. That's to say, you should get the GMT time first, then Java will add 8 hours when display time based on your pc's time zone setting.


The time zone issue is obscure, and also puzzles me for a long time. Now I make it clear. Hope helps.


2018-01-04 The method below also works.

private Date getTruncatedDate2(Date d) {
    Calendar cal = Calendar.getInstance(); // locale-specific
    cal.setTime(d);
    cal.set(Calendar.HOUR_OF_DAY, 0);
    cal.set(Calendar.MINUTE, 0);
    cal.set(Calendar.SECOND, 0);
    cal.set(Calendar.MILLISECOND, 0);


return cal.getTime();

}


Here's a simple way to get date without time if you are using Java 8+: Use java.time.LocalDate type instead of Date.

LocalDate now = LocalDate.now();
 System.out.println(now.toString());

The output:

2019-05-30

https://docs.oracle.com/javase/8/docs/api/java/time/LocalDate.html

참고URL : https://stackoverflow.com/questions/1908387/java-date-cut-off-time-information

반응형