Programing

자바 : getMinutes 및 getHours

lottogame 2020. 7. 4. 10:36
반응형

자바 : getMinutes 및 getHours


이후 어떻게 시간과 분을받을 수 있나요 Date.getHoursDate.getMinutes사용되지있어? Google 검색에서 찾은 예제는 더 이상 사용되지 않는 방법을 사용했습니다.


표준 java.util.Date 클래스 대신 Joda Time을 사용하십시오 . Joda Time 라이브러리에는 날짜 처리를위한 API가 훨씬 우수합니다.

DateTime dt = new DateTime();  // current time
int month = dt.getMonth();     // gets the current month
int hours = dt.getHourOfDay(); // gets hour of day

Joda Time 라이브러리 사용의 장단점에 대해서는이 질문참조하십시오 .

Joda Time은 표준 구성 요소로 일부 향후 버전의 Java에도 포함될 수 있습니다 ( JSR-310 참조) .


전통적인 java.util.Date 및 java.util.Calendar 클래스를 사용해야하는 경우 해당 JavaDoc의 도움말 ( java.util.Calendarjava.util.Date ) 을 참조하십시오 .

이와 같은 전통적인 클래스를 사용하여 지정된 Date 인스턴스에서 필드를 가져올 수 있습니다.

Date date = new Date();   // given date
Calendar calendar = GregorianCalendar.getInstance(); // creates a new calendar instance
calendar.setTime(date);   // assigns calendar to given date 
calendar.get(Calendar.HOUR_OF_DAY); // gets hour in 24h format
calendar.get(Calendar.HOUR);        // gets hour in 12h format
calendar.get(Calendar.MONTH);       // gets month number, NOTE this is zero based!

Date.getHours에 대한 Javadoc에서

As of JDK version 1.1, replaced by Calendar.get(Calendar.HOUR_OF_DAY)

그래서 사용

Calendar rightNow = Calendar.getInstance();
int hour = rightNow.get(Calendar.HOUR_OF_DAY);

getMinutes에 해당합니다.


java.time

난의 팬이 있지만 Joda 타임 , 자바 (8) 소개 java.time의 마지막 가치 자바 표준 솔루션 패키지를! 시간과 분이 아닌 java.time에 대한 자세한 정보는 Java SE 8 Date and Time 기사를 읽으십시오 .

특히 LocalDateTime수업을보십시오.

시간과 분 :

LocalDateTime.now().getHour();
LocalDateTime.now().getMinute();

먼저 java.util.Calendar를 가져 오십시오.

Calendar now = Calendar.getInstance();
System.out.println(now.get(Calendar.HOUR_OF_DAY) + ":" + now.get(Calendar.MINUTE));

캘린더를 사용해보십시오. getInstance를 사용하여 Calender-Object를 가져옵니다. 그런 다음 setTime을 사용하여 필요한 날짜를 설정하십시오. 이제 HOUR_OF_DAY와 같은 적절한 상수와 함께 get (int field)을 사용하여 필요한 값을 읽을 수 있습니다.

http://java.sun.com/javase/6/docs/api/java/util/Calendar.html


tl; dr

ZonedDateTime.now().getHour()

… 또는…

LocalTime.now().getHour() 

ZonedDateTime

JD답변 은 훌륭하지만 최적은 아닙니다. 그 답변은 LocalDateTime클래스를 사용합니다 . 시간대 또는 UTC에서 오프셋 개념이 없기 때문에 해당 클래스는 순간을 나타낼 수 없습니다.

사용하는 것이 좋습니다 ZonedDateTime.

ZoneId z = ZoneID.of( "America/Montreal" ) ;
ZonedDateTime zdt = ZonedDateTime.now( z ) ;

시간대 지정

ZoneId인수 를 생략하면 런타임시 JVM의 현재 기본 시간대를 사용하여 내재적으로 적용됩니다.

그래서 이거:

ZonedDateTime.now()

… 이와 동일합니다 :

ZonedDateTime.now( ZoneId.systemDefault() )

원하는 / 예상 시간대를 전달하여 명시 적으로 작성하는 것이 좋습니다. 기본값은 런타임 중에 언제든지 변경할있습니다 .

중요한 경우 사용자와 시간대를 확인하십시오.

시분

심문 ZonedDateTime시간과 분을 위해.

int hour = zdt.getHour() ;
int minute = zdt.getMinute() ;

LocalTime

시간대가없는 시간대 만 원하면을 추출하십시오 LocalTime.

LocalTime lt = zdt.toLocalTime() ;

Or skip ZonedDateTime entirely, going directly to LocalTime.

LocalTime lt = LocalTime.now( z ) ;  // Capture the current time-of-day as seen in the wall-clock time used by the people of a particular region (a time zone).

java.time types

Table of types of date-time classes in modern java.time versus legacy.


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.

To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.

The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.

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.


int hr=Time.valueOf(LocalTime.now()).getHours();
int minutes=Time.valueOf(LocalTime.now()).getMinutes();

These functions will return int values in hours and minutes.


One more way of getting minutes and hours is by using SimpleDateFormat.

SimpleDateFormat formatMinutes = new SimpleDateFormat("mm")
String getMinutes = formatMinutes.format(new Date())

SimpleDateFormat formatHours = new SimpleDateFormat("HH")
String getHours = formatHours.format(new Date())

I would recommend looking ad joda time. http://www.joda.org/joda-time/

I was afraid of adding another library to my thick project, but it's just easy and fast and smart and awesome. Plus, it plays nice with existing code, to some extent.


While I wouldn't recommend doing so, I think it's worth pointing out that although many methods on java.util.Date have been deprecated, they do still work. In trivial situations, it may be OK to use them. Also, java.util.Calendar is pretty slow, so getMonth and getYear on Date might be be usefully quicker.


public static LocalTime time() {
    LocalTime ldt = java.time.LocalTime.now();

    ldt = ldt.truncatedTo(ChronoUnit.MINUTES);
    System.out.println(ldt);
    return ldt;
}

This works for me


import java.util.*You can gethour and minute using calendar and formatter class. Calendar cal = Calendar.getInstance() and Formatter fmt=new Formatter() and set a format for display hour and minute fmt.format("%tl:%M",cal,cal)and print System.out.println(fmt) output shows like 10:12

참고URL : https://stackoverflow.com/questions/907170/java-getminutes-and-gethours

반응형