Java에서 현재 날짜 / 시간을 얻는 방법
Java에서 현재 날짜 / 시간을 얻는 가장 좋은 방법은 무엇입니까?
원하는 날짜 / 시간 형식에 따라 다릅니다.
날짜 / 시간을 단일 숫자 값으로 원하는 경우
System.currentTimeMillis()UNIX epoch 이후의 밀리 초 수 (Javalong)로 표시됩니다. 이 값은 UTC 시간 지점의 델타이며 시스템 시계가 올바르게 설정되었다고 가정 할 때 로컬 시간대와 무관합니다.구성 요소 (연도, 월 등)에 숫자로 액세스 할 수있는 형식의 날짜 / 시간을 원하는 경우 다음 중 하나를 사용할 수 있습니다.
new Date()Date현재 날짜 / 시간으로 초기화 된 객체를 제공합니다 . 문제는DateAPI 메소드가 대부분 결함이 있으며 더 이상 사용되지 않는다는 것 입니다.Calendar.getInstance()Calendar기본값Locale및을 사용하여 현재 날짜 / 시간으로 초기화 된 객체를 제공합니다TimeZone. 다른 오버로드를 사용하면 특정Locale및 / 또는TimeZone. 캘린더는 작동하지만 API는 여전히 번거 롭습니다.new org.joda.time.DateTime()기본 시간대 및 연대기를 사용하여 현재 날짜 / 시간으로 초기화 된 Joda-time 객체를 제공합니다 . 다른 Joda 대안이 많이 있습니다. 여기에서 설명하기에는 너무 많습니다. (그러나 일부 사람들은 Joda 시간에 성능 문제가 있다고보고합니다. 예를 들어 Jodatime의 LocalDateTime은 처음 사용할 때 느립니다 .)자바 8, 전화
LocalDateTime.now()및 것은ZonedDateTime.now()당신이하는 표현에 줄 것이다 일을 현재 날짜 / 시간.
Java 8 이전에 이러한 사항에 대해 아는 대부분의 사람들은 시점 및 기간 계산과 관련된 작업을 수행하는 데 가장 적합한 Java API를 보유하고 있다고 Joda-time 을 권장했습니다 . Java 8에서는 더 이상 사실이 아닙니다. 그러나 코드베이스에서 이미 Joda 시간을 사용하고 있다면 마이그레이션해야 할 강력한 두 가지 이유 가 없습니다 .
1-LocalDateTime에는 시간대가 포함되지 않습니다. javadoc에 따르면 "오프셋 또는 시간대와 같은 추가 정보 없이는 타임 라인에서 순간을 나타낼 수 없습니다."
2-그렇지 않으면 코드가 손상되지 않으며 지원 중단 경고가 표시되지 않습니다. 물론 Joda 코드베이스는 아마도 업데이트 받기를 중단 할 것이지만 업데이트가 필요하지 않을 것입니다. 업데이트가 없다는 것은 안정성을 의미하며 이는 좋은 일입니다. 또한 누군가 가 Java 플랫폼의 회귀로 인한 문제를 해결할 가능성이 높습니다 .
YYYY.MM.DD-HH.MM.SS 형식으로 타임 스탬프를 출력해야하는 경우 (매우 빈번한 경우) 다음과 같은 방법을 사용할 수 있습니다.
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(Calendar.getInstance().getTime());
현재 날짜를 문자열로 원하면 다음을 시도하십시오.
DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
Date date = new Date();
System.out.println(dateFormat.format(date));
또는
DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
Calendar cal = Calendar.getInstance();
System.out.println(dateFormat.format(cal.getTime()));
http://www.mkyong.com/java/java-how-to-get-current-date-time-date-and-calender/
에서 자바 (8) 이 있습니다 :
LocalDateTime.now()
시간대 정보가 필요한 경우 :
ZonedDateTime.now()
멋진 형식의 문자열을 인쇄하려는 경우 :
System.out.println(ZonedDateTime.now().format(DateTimeFormatter.RFC_1123_DATE_TIME))
Date 객체를 만드십시오 ...
Date date = new Date();
// 2015/09/27 15:07:53
System.out.println( new SimpleDateFormat("yyyy/MM/dd HH:mm:ss").format(Calendar.getInstance().getTime()) );
// 15:07:53
System.out.println( new SimpleDateFormat("HH:mm:ss").format(Calendar.getInstance().getTime()) );
// 09/28/2015
System.out.println(new SimpleDateFormat("MM/dd/yyyy").format(Calendar.getInstance().getTime()));
// 20150928_161823
System.out.println( new SimpleDateFormat("yyyyMMdd_HHmmss").format(Calendar.getInstance().getTime()) );
// Mon Sep 28 16:24:28 CEST 2015
System.out.println( Calendar.getInstance().getTime() );
// Mon Sep 28 16:24:51 CEST 2015
System.out.println( new Date(System.currentTimeMillis()) );
// Mon Sep 28
System.out.println( new Date().toString().substring(0, 10) );
// 2015-09-28
System.out.println( new java.sql.Date(System.currentTimeMillis()) );
// 14:32:26
Date d = new Date();
System.out.println( (d.getTime() / 1000 / 60 / 60) % 24 + ":" + (d.getTime() / 1000 / 60) % 60 + ":" + (d.getTime() / 1000) % 60 );
// 2015-09-28 17:12:35.584
System.out.println( new Timestamp(System.currentTimeMillis()) );
// Java 8
// 2015-09-28T16:16:23.308+02:00[Europe/Belgrade]
System.out.println( ZonedDateTime.now() );
// Mon, 28 Sep 2015 16:16:23 +0200
System.out.println( ZonedDateTime.now().format(DateTimeFormatter.RFC_1123_DATE_TIME) );
// 2015-09-28
System.out.println( LocalDate.now(ZoneId.of("Europe/Paris")) ); // rest zones id in ZoneId class
// 16
System.out.println( LocalTime.now().getHour() );
// 2015-09-28T16:16:23.315
System.out.println( LocalDateTime.now() );
tl; dr
Instant.now() // Capture the current moment in UTC, with a resolution of nanoseconds.
… 또는…
ZonedDateTime.now( ZoneId.of( "America/Montreal" ) ) // Capture the current moment as seen in the wall-clock time used by the people of a particular region (a time zone).
java.time
답변 중 일부는 java.time 클래스가 Java의 초기 버전과 함께 번들로 제공되는 성가신 오래된 레거시 날짜-시간 클래스를 현대적으로 대체 한다고 언급합니다 . 아래는 좀 더 많은 정보입니다.
시간대
다른 답변은 시간대가 현재 날짜와 시간을 결정하는 데 얼마나 중요한지 설명하지 못합니다. 주어진 순간에 날짜 와 시간은 지역별로 전 세계적으로 다릅니다. 예를 들어, 자정 이후 몇 분이 프랑스 파리 의 새로운 날 이지만 몬트리올 퀘벡 에서는 여전히 '어제'입니다 .
Instant
대부분의 비즈니스 로직 및 데이터 저장 / 교환은 모범 사례로 UTC 로 수행되어야합니다 .
나노초 단위 의 해상도로 UTC 로 현재 순간을 얻으려면 class를 사용하십시오 . 기존의 컴퓨터 하드웨어 시계는 정확도가 제한되어 있으므로 현재 순간을 나노초가 아닌 밀리 초 또는 마이크로 초로 캡처 할 수 있습니다.Instant
Instant instant = Instant.now();
ZonedDateTime
Instant다른 시간대로 조정할 수 있습니다 . ZoneId개체를 적용하여 ZonedDateTime.
ZoneId z = ZoneId.of( "America/Montreal" );
ZonedDateTime zdt = instant.atZone( z );
우리는 건너 뛰고 Instant전류를 ZonedDateTime직접 얻을 수 있습니다.
ZonedDateTime zdt = ZonedDateTime.now( z );
항상 선택적 시간대 인수를 전달하십시오. 생략하면 JVM의 현재 기본 시간대가 적용됩니다. 기본값은에서 변경할 수 있는 경우에도, 잠시 동안 런타임. 앱을 통제 할 수없는 외부 환경에 노출시키지 마십시오. 항상 원하는 / 예상 시간대를 지정하십시오.
ZonedDateTime do_Not_Do_This = ZonedDateTime.now(); // BAD - Never rely implicitly on the current default time zone.
당신은 나중에 추출 할 수 Instant로부터를 ZonedDateTime.
Instant instant = zdt.toInstant();
타임 라인에서 실제 순간을 원할 때 항상 Instant또는 ZonedDateTime대신 사용 LocalDateTime하십시오. Local…가 가능한 순간의 대략적인 아이디어를 표현하므로 유형이 의도적 시간대의 개념이 없습니다. 실제 순간을 얻으려면 시간대를 지정하여 Local…유형을 a 로 변환하여 ZonedDateTime의미있게 만들어야합니다.
LocalDate
LocalDate클래스는 시간이 하루의 시간 영역없이없이 날짜 만 값을 나타냅니다.
ZoneId z = ZoneId.of( "America/Montreal" );
LocalDate today = LocalDate.now( z ); // Always pass a time zone.
문자열
날짜-시간 값을 나타내는 문자열을 생성하려면 toString표준 ISO 8601 형식 에 대한 java.time 클래스를 호출 하기 만하면 됩니다.
String output = myLocalDate.toString(); // 2016-09-23
… 또는…
String output = zdt.toString(); // 2016-09-23T12:34:56.789+03:00[America/Montreal]
이 ZonedDateTime클래스는 대괄호 안에 시간대 이름을 현명하게 추가하여 표준 형식을 확장합니다.
다른 형식의 경우 Stack Overflow에서 DateTimeFormatter수업의 많은 질문과 답변을 검색하십시오 .
기피 LocalDateTime
RamanSB의 질문에 대한 의견과 달리 현재 날짜-시간에 클래스를 사용 해서는 안됩니다LocalDateTime .
은 LocalDateTime의도적으로 어떤 시간대 또는 오프셋에서-UTC 정보가 부족하다. 따라서 타임 라인에서 특정 순간을 추적 할 때는 적절 하지 않습니다 . 현재 순간을 포착하는 데는 적절 하지 않습니다 .
“로컬”이라는 표현은 반 직관적입니다. 특정 지역이 아닌 모든 지역을 의미 합니다 . 예를 들어 크리스마스는 올해 12 월 25 일 자정에 시작 : 2017-12-25T00:00:00하는로 표현되어야한다 LocalDateTime. 그러나 이것은 전 세계 여러 지점에서 다른 시간에 자정을 의미합니다. 자정은 처음에는 키리바시에서 , 나중에는 뉴질랜드에서, 몇 시간은 인도에서 발생하며, 캐나다의 아이들이 여전히 그날을 기다리고있는 프랑스에서 크리스마스가 시작되기 몇 시간이 더지나갑니다. 이러한 크리스마스 시작 지점 각각은 별도의 ZonedDateTime.
시스템 외부에서
시스템 시계를 신뢰할 수없는 경우 Java : 시스템 시계 및 내 응답이 아닌 서버에서 현재 날짜 및 시간 가져 오기를 참조하십시오 .
java.time.Clock
현재 순간의 대체 공급자를 활용하려면 추상 java.time.Clock클래스 의 하위 클래스를 작성하십시오 .
Clock구현을 다양한 java.time 메소드에 인수로 전달할 수 있습니다 . 예 : Instant.now( clock ).
Instant instant = Instant.now( yourClockGoesHere ) ;
테스트 목적의 대체 구현주의 Clock에서 정적으로 사용할 수를 Clock자체 : fixed, offset, tick, 등.
java.time 정보
java.time의 프레임 워크는 나중에 자바 8에 내장되어 있습니다. 이 클래스는 까다로운 기존에 대신 기존 과 같은 날짜 - 시간의 수업을 java.util.Date, Calendar, SimpleDateFormat.
Joda 타임 프로젝트는 지금에 유지 관리 모드 의로 마이그레이션을 조언 java.time의 클래스.
자세한 내용은 Oracle Tutorial을 참조하십시오 . 그리고 많은 예제와 설명을 위해 Stack Overflow를 검색하십시오. 사양은 JSR 310 입니다.
java.time 객체를 데이터베이스와 직접 교환 할 수 있습니다 . JDBC 4.2 이상을 준수 하는 JDBC 드라이버를 사용하십시오 . 문자열이나 클래스 가 필요하지 않습니다 .java.sql.*
java.time 클래스는 어디서 구할 수 있습니까?
- 자바 SE 8 , 자바 SE 9 , 나중에
- 내장.
- 번들로 구현 된 표준 Java API의 일부입니다.
- Java 9에는 몇 가지 사소한 기능과 수정 사항이 추가되었습니다.
- Java SE 6 및 Java SE 7
- java.time 기능의 대부분은 ThreeTen-Backport의 Java 6 및 7로 백 포트됩니다 .
- 기계적 인조 인간
- java.time 클래스의 최신 버전의 Android 번들 구현.
- 이전 Android의 경우 ThreeTenABP 프로젝트는 ThreeTen-Backport (위에서 언급)를 채택합니다 . ThreeTenABP 사용 방법…을 참조하십시오 .
ThreeTen - 추가 프로젝트 추가 클래스와 java.time를 확장합니다. 이 프로젝트는 java.time에 향후 추가 될 수있는 가능성을 입증하는 곳입니다. 당신은 여기에 몇 가지 유용한 클래스와 같은 찾을 수 있습니다 Interval, YearWeek, YearQuarter, 그리고 더 .
사용하다:
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(Calendar.getInstance().getTime());
System.out.println(timeStamp );
(작동 중입니다.)
다양한 방법이 있습니다.
날짜 개체를 만들고 간단히 인쇄하십시오.
Date d = new Date(System.currentTimeMillis());
System.out.print(d);
위의 솔루션과 유사합니다. 하지만 저는 항상이 코드 덩어리를 찾고 있습니다.
Date date=Calendar.getInstance().getTime();
System.out.println(date);
java.util.Date를 보셨습니까? 정확히 당신이 원하는 것입니다.
java.util.Date date = new java.util.Date();
인스턴스화되는 시간에 자동으로 채워집니다.
1st java.util.Date 클래스 이해
1.1 현재 날짜를 얻는 방법
import java.util.Date;
class Demostration{
public static void main(String[]args){
Date date = new Date(); // date object
System.out.println(date); // Try to print the date object
}
}
1.2 getTime () 메서드 사용 방법
import java.util.Date;
public class Main {
public static void main(String[]args){
Date date = new Date();
long timeInMilliSeconds = date.getTime();
System.out.println(timeInMilliSeconds);
}
}
시간 비교 목적으로 1970 년 1 월 1 일 00:00:00 GMT 이후의 밀리 초 수를 반환합니다.
1.3 SimpleDateFormat 클래스를 사용하여 시간 형식을 지정하는 방법
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
class Demostration{
public static void main(String[]args){
Date date=new Date();
DateFormat dateFormat=new SimpleDateFormat("yyyy-MM-dd");
String formattedDate=dateFormat.format(date);
System.out.println(formattedDate);
}
}
또한 "yyyy-MM-dd hh : mm : ss"와 같은 다른 형식 패턴을 사용해보고 원하는 패턴을 선택합니다. http://docs.oracle.com/javase/7/docs/api/java/text/SimpleDateFormat.html
2nd java.util.Calendar 클래스 이해
2.1 캘린더 클래스를 사용하여 현재 타임 스탬프 얻기
import java.util.Calendar;
class Demostration{
public static void main(String[]args){
Calendar calendar=Calendar.getInstance();
System.out.println(calendar.getTime());
}
}
2.2 다른 날짜로 달력을 설정하려면 setTime 및 기타 설정 방법을 사용해보십시오.
출처 : http://javau91.blogspot.com/
java.util.Date의 경우 새 Date ()를 만듭니다.
DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
Date date = new Date();
System.out.println(dateFormat.format(date)); //2016/11/16 12:08:43
java.util.Calendar의 경우 Calendar.getInstance () 사용
DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
Calendar cal = Calendar.getInstance();
System.out.println(dateFormat.format(cal)); //2016/11/16 12:08:43
java.time.LocalDateTime의 경우 LocalDateTime.now () 사용
DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyy/MM/dd HH:mm:ss");
LocalDateTime now = LocalDateTime.now();
System.out.println(dtf.format(now)); //2016/11/16 12:08:43
java.time.LocalDate의 경우 LocalDate.now () 사용
DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyy/MM/dd");
LocalDate localDate = LocalDate.now();
System.out.println(dtf.format(localDate)); //2016/11/16
참조 : https://www.mkyong.com/java/java-how-to-get-current-date-time-date-and-calender/
이것이 최선의 방법이라고 생각합니다.
DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
Calendar cal = Calendar.getInstance();
System.out.println(dateFormat.format(cal.getTime())); // 2014/08/06 16:00:22
사용하다:
SimpleDateFormat sdf = new SimpleDateFormat("yyyy:MM:dd::HH:mm:ss");
System.out.println(sdf.format(System.currentTimeMillis()));
print 문은 생성 된 시간이 아니라 호출 된 시간을 인쇄합니다 SimpleDateFormat. 따라서 새로운 객체를 생성하지 않고 반복적으로 호출 할 수 있습니다.
Date 클래스를 살펴보십시오 . 또한 많은 날짜 / 시간 작업을 수행하는 데 선호되는 방법 인 최신 Calendar 클래스 도 있습니다 (Date의 많은 메서드가 더 이상 사용되지 않음).
현재 날짜 만 원하는 경우 새 Date 객체를 만들거나 Calendar.getInstance();.
언급했듯이 기본 Date ()는 현재 시간을 얻는 데 필요한 작업을 수행 할 수 있습니다. 최근 Java 날짜를 많이 사용하는 경험에서 내장 클래스에 많은 이상한 점이 있습니다 (많은 Date 클래스 메서드의 사용 중단). 나에게 눈에 띄는 한 가지 이상한 점은 기술적 인 관점에서 볼 때 의미가 있지만 실제로는 매우 혼란 스러울 수있는 0 인덱스 기반이라는 것입니다.
충분한 현재 날짜에만 관심이 있다면-그러나 날짜를 사용하여 많은 조작 / 계산을 수행하려는 경우 타사 라이브러리를 사용하는 것이 매우 유용 할 수 있습니다 (많은 Java 개발자가 내장 기능).
나는 Joda-time이 날짜로 작업을 단순화하는 데 매우 유용하다는 것을 알았 기 때문에 Stephen C의 추천을 두 번째로 받았습니다. 또한 매우 잘 문서화되어 있으며 웹에서 많은 유용한 예제를 찾을 수 있습니다. 나는 모든 일반적인 날짜 조작을 통합하고 단순화하는 데 사용하는 정적 래퍼 클래스 (DateUtils)를 작성하기도했습니다.
새로운 Data-Time API는 Java 8의 시작과 함께 도입되었습니다. 이는 이전 Data-Time API에서 발생했던 다음과 같은 문제 때문입니다.
시간대 처리 어려움 : 시간대를 처리하기 위해 많은 코드를 작성해야합니다.
스레드로부터 안전하지 않음 : java.util.Date는 스레드로부터 안전하지 않습니다.
따라서 Java 8을 살펴보십시오.
import java.time.LocalDate;
import java.time.LocalTime;
import java.time.LocalDateTime;
import java.time.Month;
public class DataTimeChecker {
public static void main(String args[]) {
DataTimeChecker dateTimeChecker = new DataTimeChecker();
dateTimeChecker.DateTime();
}
public void DateTime() {
// Get the current date and time
LocalDateTime currentTime = LocalDateTime.now();
System.out.println("Current DateTime: " + currentTime);
LocalDate date1 = currentTime.toLocalDate();
System.out.println("Date : " + date1);
Month month = currentTime.getMonth();
int day = currentTime.getDayOfMonth();
int seconds = currentTime.getSecond();
System.out.println("Month : " + month);
System.out.println("Day : " + day);
System.out.println("Seconds : " + seconds);
LocalDateTime date2 = currentTime.withDayOfMonth(17).withYear(2018);
System.out.println("Date : " + date2);
//Prints 17 May 2018
LocalDate date3 = LocalDate.of(2018, Month.MAY, 17);
System.out.println("Date : " + date3);
//Prints 04 hour 45 minutes
LocalTime date4 = LocalTime.of(4, 45);
System.out.println("Date : " + date4);
// Convert to a String
LocalTime date5 = LocalTime.parse("20:15:30");
System.out.println("Date : " + date5);
}
}
위의 코딩 결과 :
Current DateTime: 2018-05-17T04:40:34.603
Date : 2018-05-17
Month : MAY
Day : 17
Seconds : 34
Date : 2018-05-17T04:40:34.603
Date : 2018-05-17
Date : 04:45
Date : 20:15:30
System.out.println( new SimpleDateFormat("yyyy:MM:dd - hh:mm:ss a").format(Calendar.getInstance().getTime()) );
//2018:02:10 - 05:04:20 PM
오전 / 오후 날짜 / 시간
import java.util.*;
import java.text.*;
public class DateDemo {
public static void main(String args[]) {
Date dNow = new Date( );
SimpleDateFormat ft =
new SimpleDateFormat ("E yyyy.MM.dd 'at' hh:mm:ss a zzz");
System.out.println("Current Date: " + ft.format(dNow));
}
}
현재 데이터에 날짜를 사용할 수 있습니다. 그래서
SimpleDateFormat형식 가져 오기 사용
이 방법을 만들었습니다. 저에게 효과적입니다 ...
public String GetDay() {
return String.valueOf(LocalDateTime.now().format(DateTimeFormatter.ofPattern("dd")));
}
public String GetNameOfTheDay() {
return String.valueOf(LocalDateTime.now().getDayOfWeek());
}
public String GetMonth() {
return String.valueOf(LocalDateTime.now().format(DateTimeFormatter.ofPattern("MM")));
}
public String GetNameOfTheMonth() {
return String.valueOf(LocalDateTime.now().getMonth());
}
public String GetYear() {
return String.valueOf(LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy")));
}
public boolean isLeapYear(long year) {
return Year.isLeap(year);
}
public String GetDate() {
return GetDay() + "/" + GetMonth() + "/" + GetYear();
}
public String Get12HHour() {
return String.valueOf(LocalDateTime.now().format(DateTimeFormatter.ofPattern("hh")));
}
public String Get24HHour() {
return String.valueOf(LocalDateTime.now().getHour());
}
public String GetMinutes() {
return String.valueOf(LocalDateTime.now().format(DateTimeFormatter.ofPattern("mm")));
}
public String GetSeconds() {
return String.valueOf(LocalDateTime.now().format(DateTimeFormatter.ofPattern("ss")));
}
public String Get24HTime() {
return Get24HHour() + ":" + GetMinutes();
}
public String Get24HFullTime() {
return Get24HHour() + ":" + GetMinutes() + ":" + GetSeconds();
}
public String Get12HTime() {
return Get12HHour() + ":" + GetMinutes();
}
public String Get12HFullTime() {
return Get12HHour() + ":" + GetMinutes() + ":" + GetSeconds();
}
Date개체 및 서식을 직접 사용할 수 있습니다 . 예를 들어 포맷하기가 어렵고 더 많은 코드가 필요합니다.
Date dateInstance = new Date();
int year = dateInstance.getYear()+1900;//Returns:the year represented by this date, minus 1900.
int date = dateInstance.getDate();
int month = dateInstance.getMonth();
int day = dateInstance.getDay();
int hours = dateInstance.getHours();
int min = dateInstance.getMinutes();
int sec = dateInstance.getSeconds();
String dayOfWeek = "";
switch(day){
case 0:
dayOfWeek = "Sunday";
break;
case 1:
dayOfWeek = "Monday";
break;
case 2:
dayOfWeek = "Tuesday";
break;
case 3:
dayOfWeek = "Wednesday";
break;
case 4:
dayOfWeek = "Thursday";
break;
case 5:
dayOfWeek = "Friday";
break;
case 6:
dayOfWeek = "Saturday";
break;
}
System.out.println("Date: " + year +"-"+ month + "-" + date + " "+ dayOfWeek);
System.out.println("Time: " + hours +":"+ min + ":" + sec);
산출:
Date: 2017-6-23 Sunday
Time: 14:6:20
보시다시피 이것은 최악의 방법이며 오라클 문서에 따르면 더 이상 사용되지 않습니다 .
Oracle 문서 :
Date 클래스는 밀리 초 정밀도로 특정 순간을 나타냅니다.
JDK 1.1 이전에는 Date 클래스에 두 가지 추가 기능이있었습니다. 날짜를 년, 월, 일,시, 분 및 초 값으로 해석 할 수 있습니다. 또한 날짜 문자열의 형식화 및 구문 분석을 허용했습니다. 불행히도 이러한 기능에 대한 API는 국제화에 적합하지 않았습니다. JDK 1.1부터는 Calendar 클래스를 사용하여 날짜와 시간 필드를 변환해야하고 DateFormat 클래스를 사용하여 날짜 문자열을 형식화하고 구문 분석해야합니다. Date의 해당 메서드는 더 이상 사용되지 않습니다.
따라서 대안으로 Calendar클래스 를 사용할 수 있습니다 .
Calendar.YEAR;
//and lot more
현재 시간을 얻으려면 다음을 사용할 수 있습니다.
Calendar rightNow = Calendar.getInstance();
문서:
로케일에 민감한 다른 클래스와 마찬가지로이 유형의 일반적으로 유용한 객체를 가져 오기위한
Calendar클래스 메서드를 제공합니다getInstance. 달력의getInstance메서드는Calendar달력 필드가 현재 날짜 및 시간으로 초기화 된 객체를 반환합니다.
날짜 만 가져 오려면 아래 코드
Date rightNow = Calendar.getInstance().getTime();
System.out.println(rightNow);
또한 Calendar클래스에는 하위 클래스가 있습니다. GregorianCalendar그들 중 하나이며의 구체적인 하위 클래스이며 Calendar대부분의 세계에서 사용되는 표준 달력 시스템을 제공합니다.
사용 예 GregorianCalendar:
Calendar cal = new GregorianCalendar();
int hours = cal.get(Calendar.HOUR);
int minute = cal.get(Calendar.MINUTE);
int second = cal.get(Calendar.SECOND);
int ap = cal.get(Calendar.AM_PM);
String amVSpm;
if(ap == 0){
amVSpm = "AM";
}else{
amVSpm = "PM";
}
String timer = hours + "-" + minute + "-" + second + " " +amVSpm;
System.out.println(timer);
SimpleDateFormat, 간단하고 빠른 방법으로 날짜 형식을 지정할 수 있습니다 .
String pattern = "yyyy-MM-dd";
SimpleDateFormat simpleDateFormat = new SimpleDateFormat(pattern);
String date = simpleDateFormat.format(new Date());
System.out.println(date);
Jakob Jenkov 튜토리얼 : Java SimpleDateFormat을 읽으십시오 .
다른 사람들이 언급했듯이 날짜를 조작해야 할 때 간단하고 최선의 방법이 없었거나 내장 된 클래스, API를 만족할 수 없었습니다.
예를 들어, 두 날짜 사이에 차이를 가져와야 할 때, 두 날짜 를 비교 해야 할 때 (이에 대한 내장 메서드도 있음) 등 이 있습니다. 타사 라이브러리를 사용해야했습니다. 좋고 인기있는 것 중 하나는 Joda Time입니다.
또한 읽으십시오 :
. 가장 행복한 것은 (Java 8에서) 아무도 어떤 이유로 든 라이브러리를 다운로드하고 사용할 필요가 없다는 것입니다. Java 8에서 현재 날짜 및 시간을 얻는 간단한 예,
LocalTime localTime = LocalTime.now();
System.out.println(localTime);
//with time zone
LocalTime localTimeWtZone = LocalTime.now(ZoneId.of("GMT+02:30"));
System.out.println(localTimeWtZone);
Java 8 날짜에 대해 읽을 수 있는 좋은 블로그 게시물 중 하나입니다 .
Java 날짜 및 시간에 대해 자세히 알아 보려면 계속 기억하십시오. 구하거나 사용할 수있는 방법 및 / 또는 유용한 방법이 훨씬 더 많기 때문입니다.
편집하다:
@BasilBourque 의견에 따르면, 같은 귀찮은 된 날짜 - 시간 수업 java.util.Date, java.util.Calendar그리고 java.text.SimpleTextFormat지금 기존 에 의해 대체, java.time클래스 .
같은 질문을 받았을 때 필요한 모든 것이기 때문에 계속 해서이 답변을 던질 것입니다.
Date currentDate = new Date(System.currentTimeMillis());
currentDate이제 Java Date객체 의 현재 날짜입니다 .
이 코드를 시도하십시오.
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
public class CurrentTimeDateCalendar {
public static void getCurrentTimeUsingDate() {
Date date = new Date();
String strDateFormat = "hh:mm:ss a";
DateFormat dateFormat = new SimpleDateFormat(strDateFormat);
String formattedDate= dateFormat.format(date);
System.out.println("Current time of the day using Date - 12 hour format: " + formattedDate);
}
public static void getCurrentTimeUsingCalendar() {
Calendar cal = Calendar.getInstance();
Date date=cal.getTime();
DateFormat dateFormat = new SimpleDateFormat("HH:mm:ss");
String formattedDate=dateFormat.format(date);
System.out.println("Current time of the day using Calendar - 24 hour format: "+ formattedDate);
}
}
샘플 출력은 다음과 같습니다.
날짜를 사용하는 현재 시간-12 시간 형식 : 오후 11:13:01
캘린더를 사용하는 현재 시간-24 시간 형식 : 23:13:01
자세한 정보 :
참고 URL : https://stackoverflow.com/questions/5175728/how-to-get-the-current-date-time-in-java
'Programing' 카테고리의 다른 글
| SQL은 SELECT * [columnA 제외] FROM tableA를 사용하여 열을 제외합니까? (0) | 2020.10.02 |
|---|---|
| IEnumerable의 동적 LINQ OrderBy (0) | 2020.10.02 |
| PyPy가 6.3 배 빠르면 CPython을 통해 PyPy를 사용하지 않는 이유는 무엇입니까? (0) | 2020.10.02 |
| HttpClient 요청에 대한 Content-Type 헤더를 어떻게 설정합니까? (0) | 2020.10.02 |
| Java에서 기존 파일에 텍스트를 추가하는 방법 (0) | 2020.10.02 |

