Programing

현재 시간을 가져 오는 Java 코드

lottogame 2020. 6. 12. 22:07
반응형

현재 시간을 가져 오는 Java 코드


이 질문에는 이미 답변이 있습니다.

java로컬 PC 시스템 시간을 가져 와서 응용 프로그램으로 동기화하기 위해 코드를 검색하고 있습니다 .


이 시도:

import java.text.SimpleDateFormat;
import java.util.Calendar;

public class currentTime {

    public static void main(String[] args) {
        Calendar cal = Calendar.getInstance();
        SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss");
        System.out.println( sdf.format(cal.getTime()) );
    }

}

원하는 방식으로 SimpleDateFormat을 포맷 할 수 있습니다. 추가 정보는 java api에서 확인할 수 있습니다.

SimpleDateFormat

달력


양자 모두

new java.util.Date()

System.currentTimeMillis()

현재 시스템 시간을 제공합니다.


tl; dr

Instant.now()  // UTC

…또는…

ZonedDateTime.now(
    // Specify time zone.
    ZoneId.of( "Pacific/Auckland" )
)  

세부

번들 java.util.Date/ .Calendar클래스는 악명 높은 것으로 악명이 높습니다. 피하십시오. 이것들은 이제 java.time 프레임 워크에 의해 대체 된 레거시 입니다.

대신 다음 중 하나를 사용하십시오.

java.time

ZonedDateTime zdt = ZonedDateTime.now();

이전 코드에 필요한 경우 java.util.Date로 변환하십시오. UTCInstant 의 타임 라인에있는 순간 을 살펴보십시오 .

java.util.Date date = java.util.Date.from( zdt.toInstant() );

시간대

JVM의 현재 기본 시간대 에 내재적으로 의존하지 않고 원하는 / 예상 시간대 를 명시 적으로 지정 하는 것이 좋습니다 .

ZoneId zoneId = ZoneId.of( "America/Montreal" );
ZonedDateTime zdt = ZonedDateTime.now( zoneId );  // Pass desired/expected time zone.

조다 타임

참고로 Joda-Time 프로젝트는 이제 유지 관리 모드 에 있으며 팀은 java.time 클래스 로의 마이그레이션을 조언합니다 .

DateTime now = DateTime.now();

Joda-Time DateTime 객체를 다른 클래스와 상호 운용하기 위해 java.util.Date 로 변환하려면

java.util.Date date = now.toDate();

게시하기 전에 StackOverflow를 검색하십시오. 귀하의 질문은 이미 요청 및 답변되었습니다.


java.time에 대하여

java.time의 프레임 워크는 나중에 자바 8에 내장되어 있습니다. 이 클래스는 까다로운 기존에 대신 기존 과 같은 날짜 - 시간의 수업을 java.util.Date, Calendar, SimpleDateFormat.

Joda 타임 프로젝트는 지금에 유지 관리 모드 의로 마이그레이션을 조언 java.time의 클래스.

자세한 내용은 Oracle Tutorial을 참조하십시오 . 많은 예제와 설명을 보려면 스택 오버플로를 검색하십시오. 사양은 JSR 310 입니다.

java.time 클래스는 어디서 구할 수 있습니까?

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.


System.currentTimeMillis()

everything else works off that.. eg new Date() calls System.currentTimeMillis().


Try this way, more efficient and compatible:

SimpleDateFormat time_formatter = new SimpleDateFormat("yyyy-MM-dd_HH:mm:ss.SSS");
String current_time_str = time_formatter.format(System.currentTimeMillis());
//Log.i("test", "current_time_str:" + current_time_str);

Just to inform for furthers developers, and thankfully to Basil Bourque, I just wanna add my stone to this topic.

If you want simply get the HH:MM:SS format then do this:

LocalTime hour = ZonedDateTime.now().toLocalTime().truncatedTo(ChronoUnit.SECONDS);

Cheers.

P.S.: This will work only at least with Java 8 !


Like said above you can use

Date d = new Date();

or use

Calendar.getInstance();

or if you want it in millis

System.currentTimeMillis()

Not really sure about what you meant, but you probably just need

Date d = new Date();

try this:

final String currentTime    = String.valueOf(System.currentTimeMillis());

You can use new Date () and it'll give you current time.

If you need to represent it in some format (and usually you need to do it) then use formatters.

DateFormat df = DateFormat.getDateTimeInstance (DateFormat.MEDIUM, DateFormat.MEDIUM, new Locale ("en", "EN"));
String formattedDate = df.format (new Date ());

new Date().getTime() is bugged.

    Date date = new Date();
    System.out.println(date);
    System.out.println(date.getHours() + ":" + date.getMinutes() + ":" + date.getSeconds());
    long t1 = date.getTime();
    System.out.println((t1 / 1000 / 60 / 60) % 24 + ":" + (t1 / 1000 / 60) % 60 + ":" + (t1 / 1000) % 60);
    long t2 = System.currentTimeMillis();
    System.out.println((t2 / 1000 / 60 / 60) % 24 + ":" + (t2 / 1000 / 60) % 60 + ":" + (t2 / 1000) % 60);

It returns me the wrong time millis. System.currentTimeMillis() too. Since I ask the Date instance to tell me the corresponding time millis it must return the matching ones not others from a different time zone. Funny how deprecated methods are the only ones which return correct values.


To get system time use Calendar.getInstance().getTime()

And you should get the new instance of Calendar each time to have current time.

To change system time from java code you can use a command line


I understand this is quite an old question. But would like to clarify that:

Date d = new Date() 

is depriciated in the current versions of Java. The recommended way is using a calendar object. For eg:

Calendar cal = Calendar.getInstance();
Date currentTime = cal.getTime();

I hope this will help people who may refer this question in future. Thank you all.


try this to get the current date.You can also get current hour, minutes and seconds by using getters :

new Date(System.currentTimeMillis()).get....()

참고URL : https://stackoverflow.com/questions/833768/java-code-for-getting-current-time

반응형