시간을 00:00:00으로 설정
Java에서 시간을 재설정하는 데 문제가 있습니다. 주어진 날짜에 시간을 00:00:00으로 설정하고 싶습니다.
이것은 내 코드입니다.
/**
* Resets milliseconds, seconds, minutes and hours from the provided date
*
* @param date
* @return
*/
public static Date trim(Date date) {
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
calendar.set(Calendar.MILLISECOND, 0);
calendar.set(Calendar.SECOND, 0);
calendar.set(Calendar.MINUTE, 0);
calendar.set(Calendar.HOUR, 0);
return calendar.getTime();
}
문제는 때로는 시간이 지남에 따라 12:00:00
때로는 00:00:00
저장된 엔터티에 대해 데이터베이스를 쿼리 할 때 07.02.2013 00:00:00
실제 엔터티 시간이 저장된 12:00:00
경우 쿼리가 실패 한다는 것입니다 .
알아요 12:00:00 == 00:00:00
!
AppEngine을 사용하고 있습니다. 이것이 appengine 버그, 문제 또는 다른 문제입니까? 아니면 다른 것에 의존합니까?
대신에 다른 일정 사용하여 Calendar.HOUR
사용을 Calendar.HOUR_OF_DAY
.
calendar.set(Calendar.HOUR_OF_DAY, 0);
Calendar.HOUR
0-11을 사용하고 (AM / PM과 함께 Calendar.HOUR_OF_DAY
사용) 0-23을 사용합니다.
Javadoc을 인용하려면 :
공개 정적 최종 int HOUR
오전 또는 오후의 시간을 나타내는 get 및 set의 필드 번호. HOUR는 12 시간제 (0-11)에 사용됩니다. 정오와 자정은 12가 아니라 0으로 표시됩니다. 예를 들어 오후 10 : 04 : 15.250에 HOUR는 10입니다.
과
공개 정적 최종 int HOUR_OF_DAY
하루 중 시간을 나타내는 get 및 set의 필드 번호. HOUR_OF_DAY는 24 시간 제로 사용됩니다. 예를 들어 오후 10 : 04 : 15.250에 HOUR_OF_DAY는 22입니다.
테스트 ( '현재'는 2013 년 7 월 23 일 태평양 일광 절약 시간 기준으로 현재 14:55입니다) :
public class Main
{
static SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
public static void main(String[] args)
{
Calendar now = Calendar.getInstance();
now.set(Calendar.HOUR, 0);
now.set(Calendar.MINUTE, 0);
now.set(Calendar.SECOND, 0);
System.out.println(sdf.format(now.getTime()));
now.set(Calendar.HOUR_OF_DAY, 0);
System.out.println(sdf.format(now.getTime()));
}
}
산출:
$ javac Main.java
$ java Main
2013-07-23 12:00:00
2013-07-23 00:00:00
java.time
java.time
Java 8 이상에 내장 된 프레임 워크 사용 튜토리얼을 참조하십시오 .
import java.time.LocalTime;
import java.time.LocalDateTime;
LocalDateTime now = LocalDateTime.now(); # 2015-11-19T19:42:19.224
# start of a day
now.with(LocalTime.MIN); # 2015-11-19T00:00
now.with(LocalTime.MIDNIGHT); # 2015-11-19T00:00
시간 (시간, 분, 초 등)이 필요하지 않은 경우 LocalDate
수업 사용을 고려하십시오 .
LocalDate.now(); # 2015-11-19
다음은이 작업을 수행하는 데 사용되는 몇 가지 유틸리티 기능입니다.
/**
* sets all the time related fields to ZERO!
*
* @param date
*
* @return Date with hours, minutes, seconds and ms set to ZERO!
*/
public static Date zeroTime( final Date date )
{
return DateTimeUtil.setTime( date, 0, 0, 0, 0 );
}
/**
* Set the time of the given Date
*
* @param date
* @param hourOfDay
* @param minute
* @param second
* @param ms
*
* @return new instance of java.util.Date with the time set
*/
public static Date setTime( final Date date, final int hourOfDay, final int minute, final int second, final int ms )
{
final GregorianCalendar gc = new GregorianCalendar();
gc.setTime( date );
gc.set( Calendar.HOUR_OF_DAY, hourOfDay );
gc.set( Calendar.MINUTE, minute );
gc.set( Calendar.SECOND, second );
gc.set( Calendar.MILLISECOND, ms );
return gc.getTime();
}
하나 더 자바 8 방법 :
LocalDateTime localDateTime = LocalDateTime.now().truncatedTo(ChronoUnit.HOURS);
But it's a lot more useful to edit the date that already exists.
You would better to primarily set time zone to the DateFormat component like this:
DateFormat dateFormat = new SimpleDateFormat("HH:mm:ss");
dateFormat.setTimeZone(TimeZone.getTimeZone("GMT"));
Then you can get "00:00:00" time by passing 0 milliseconds to formatter:
String time = dateFormat.format(0);
or you can create Date object:
Date date = new Date(0); // also pass milliseconds
String time = dateFormat.foramt(date);
or you be able to have more possibilities using Calendar component but you should also set timezone as GMT to calendar instance:
Calendar calendar = Calendar.getInstance(TimeZone.getTimeZone("GMT"), Locale.US);
calendar.set(Calendar.HOUR_OF_DAY, 5);
calendar.set(Calendar.MINUTE, 37);
calendar.set(Calendar.SECOND, 27);
dateFormat.format(calendar.getTime());
tl;dr
myJavaUtilDate // The terrible `java.util.Date` class is now legacy. Use *java.time* instead.
.toInstant() // Convert this moment in UTC from the legacy class `Date` to the modern class `Instant`.
.atZone( ZoneId.of( "Africa/Tunis" ) ) // Adjust from UTC to the wall-clock time used by the people of a particular region (a time zone).
.toLocalDate() // Extract the date-only portion.
.atStartOfDay( ZoneId.of( "Africa/Tunis" ) ) // Determine the first moment of that date in that zone. The day does *not* always start at 00:00:00.
java.time
You are using terrible old date-time classes that were supplanted years ago by the modern java.time classes defined in JSR 310.
Date
➙ Instant
A java.util.Date
represent a moment in UTC. Its replacement is Instant
. Call the new conversion methods added to the old classes.
Instant instant = myJavaUtilDate.toInstant() ;
Time zone
Specify the time zone in which you want your new time-of-day to make sense.
Specify a proper time zone name in the format of Continent/Region
, such as America/Montreal
, Africa/Casablanca
, or Pacific/Auckland
. Never use the 2-4 letter abbreviation such as EST
or IST
as they are not true time zones, not standardized, and not even unique(!).
ZoneId z = ZoneId.of( "America/Montreal" ) ;
ZonedDateTime
Apply the ZoneId
to the Instant
to get a ZonedDateTime
. Same moment, same point on the timeline, but different wall-clock time.
ZonedDateTime zdt = instant.atZone( z ) ;
Changing time-of-day
You asked to change the time-of-day. Apply a LocalTime
to change all the time-of-day parts: hour, minute, second, fractional second. A new ZonedDateTime
is instantiated, with values based on the original. The java.time classes use this immutable objects pattern to provide thread-safety.
LocalTime lt = LocalTime.of( 15 , 30 ) ; // 3:30 PM.
ZonedDateTime zdtAtThreeThirty = zdt.with( lt ) ;
First moment of day
But you asked specifically for 00:00. So apparently you want the first moment of the day. Beware: some days in some zones do not start at 00:00:00. They may start at another time such as 01:00:00 because of anomalies such as Daylight Saving Time (DST).
Let java.time determine the first moment. Extract the date-only portion. Then pass the time zone to get first moment.
LocalDate ld = zdt.toLocalDate() ;
ZonedDateTime zdtFirstMomentOfDay = ld.atStartOfDay( z ) ;
Adjust to UTC
If you need to go back to UTC, extract an Instant
.
Instant instant = zdtFirstMomentOfDay.toInstant() ;
Instant
➙ Date
If you need a java.util.Date
to interoperate with old code not yet updated to java.time, convert.
java.util.Date d = java.util.Date.from( instant ) ;
Doing this could be easier (In Java 8)
LocalTime.ofNanoOfDay(0)
We can set java.util.Date time part to 00:00:00 By using LocalDate class of Java 8/Joda-datetime api:
Date datewithTime = new Date() ; // ex: Sat Apr 21 01:30:44 IST 2018
LocalDate localDate = LocalDate.fromDateFields(datewithTime);
Date datewithoutTime = localDate.toDate(); // Sat Apr 21 00:00:00 IST 2018
Another way to do this would be to use a DateFormat without any seconds:
public static Date trim(Date date) {
DateFormat format = new SimpleDateFormat("dd.MM.yyyy");
Date trimmed = null;
try {
trimmed = format.parse(format.format(date));
} catch (ParseException e) {} // will never happen
return trimmed;
}
You can either do this with the following:
Calendar cal = Calendar.getInstance();
cal.set(year, month, dayOfMonth, 0, 0, 0);
Date date = cal.getTime();
If you need format 00:00:00 in string, you should use SimpleDateFormat as below. Using "H "instead "h".
Date today = new Date();
SimpleDateFormat ft = new SimpleDateFormat("dd-MM-yyyy HH:mm:ss");
//not SimpleDateFormat("dd-MM-yyyy hh:mm:ss")
Calendar calendarDM = Calendar.getInstance();
calendarDM.setTime(today);
calendarDM.set(Calendar.HOUR, 0);
calendarDM.set(Calendar.MINUTE, 0);
calendarDM.set(Calendar.SECOND, 0);
System.out.println("Current Date: " + ft.format(calendarDM.getTime()));
//Result is: Current Date: 29-10-2018 00:00:00
As Java8 add new Date functions, we can do this easily.
// If you have instant, then:
Instant instant1 = Instant.now();
Instant day1 = instant1.truncatedTo(ChronoUnit.DAYS);
System.out.println(day1); //2019-01-14T00:00:00Z
// If you have Date, then:
Date date = new Date();
Instant instant2 = date.toInstant();
Instant day2 = instant2.truncatedTo(ChronoUnit.DAYS);
System.out.println(day2); //2019-01-14T00:00:00Z
// If you have LocalDateTime, then:
LocalDateTime dateTime = LocalDateTime.now();
LocalDateTime day3 = dateTime.truncatedTo(ChronoUnit.DAYS);
System.out.println(day3); //2019-01-14T00:00
String format = day3.format(DateTimeFormatter.ISO_LOCAL_DATE_TIME);
System.out.println(format);//2019-01-14T00:00:00
참고URL : https://stackoverflow.com/questions/17821601/set-time-to-000000
'developer tip' 카테고리의 다른 글
Windows 명령 프롬프트에서 LS를 만드는 방법은 무엇입니까? (0) | 2020.08.02 |
---|---|
PHP에서 배열 요소의 키를 재설정 하시겠습니까? (0) | 2020.08.02 |
Ruby에서 변수가 문자열인지 확인 (0) | 2020.07.30 |
Intellij IDEA 2016.1.1의 콘솔에 Gradle 출력 표시 (0) | 2020.07.30 |
jQuery 슬라이드 왼쪽 및 표시 (0) | 2020.07.30 |