your programing

Android에서 현재 시간 및 날짜 가져 오기

lovepro 2020. 9. 27. 13:35
반응형

Android에서 현재 시간 및 날짜 가져 오기


Android 앱에서 현재 시간과 날짜를 어떻게 알 수 있습니까?


다음을 사용할 수 있습니다.

import java.util.Calendar

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

캘린더에는 필요한 모든 것을위한 많은 상수가 있습니다.

편집 : 캘린더 클래스 문서
확인


android.text.format.Time을 사용할 수 있습니다 ( 더 이상은 안됩니다 -아래 참조!) .

Time now = new Time();
now.setToNow();

위에 링크 된 참조에서 :

Time 클래스는 java.util.Calendar 및 java.util.GregorianCalendar 클래스를 더 빠르게 대체합니다. Time 클래스의 인스턴스는 초 정밀도로 지정된 시간을 나타냅니다.


참고 1 : 이 답변을 작성한 지 몇 년이 지났으며 오래된 Android 전용이며 현재는 더 이상 사용되지 않는 클래스에 관한 것입니다. 구글은 지금 말한다 "[t]가 자신의 클래스는 문제의 번호를 가지고 있으며이 것이 좋습니다 것을 GregorianCalendar를가 대신 사용됩니다."


참고 2 :Time 클래스에 toMillis(ignoreDaylightSavings)메서드 있어도 밀리 초 단위의 시간을 예상하는 메서드에 전달하는 것은 편리합니다. 시간 값은 1 초까지만 정확합니다 . 밀리 초 부분은 항상 000입니다. 루프에 있다면

Time time = new Time();   time.setToNow();
Log.d("TIME TEST", Long.toString(time.toMillis(false)));
... do something that takes more than one millisecond, but less than one second ...

결과 시퀀스는 1410543204000다음 1 초가 시작될 때까지 같은 값 1410543205000을 반복합니다.


특정 패턴으로 날짜와 시간을 얻으려면 다음을 사용할 수 있습니다.

SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd_HHmmss", Locale.getDefault());
String currentDateandTime = sdf.format(new Date());

또는,

날짜 :

String currentDate = new SimpleDateFormat("dd-MM-yyyy", Locale.getDefault()).format(new Date());

시각:

String currentTime = new SimpleDateFormat("HH:mm:ss", Locale.getDefault()).format(new Date());

사용자 정의 형식을 선호하는 사람들을 위해 다음을 사용할 수 있습니다.

DateFormat df = new SimpleDateFormat("EEE, d MMM yyyy, HH:mm");
String date = df.format(Calendar.getInstance().getTime());

반면 다음과 같은 DateFormat 패턴을 가질 수 있습니다.

"yyyy.MM.dd G 'at' HH:mm:ss z" ---- 2001.07.04 AD at 12:08:56 PDT
"hh 'o''clock' a, zzzz" ----------- 12 o'clock PM, Pacific Daylight Time
"EEE, d MMM yyyy HH:mm:ss Z"------- Wed, 4 Jul 2001 12:08:56 -0700
"yyyy-MM-dd'T'HH:mm:ss.SSSZ"------- 2001-07-04T12:08:56.235-0700
"yyMMddHHmmssZ"-------------------- 010704120856-0700
"K:mm a, z" ----------------------- 0:08 PM, PDT
"h:mm a" -------------------------- 12:08 PM
"EEE, MMM d, ''yy" ---------------- Wed, Jul 4, '01

실제로 기기에 설정된 현재 시간대를으로 설정하는 것이 더 안전합니다. Time.getCurrentTimezone()그렇지 않으면 UTC로 현재 시간을 얻을 수 있습니다.

Time today = new Time(Time.getCurrentTimezone());
today.setToNow();

그런 다음 다음과 같이 원하는 모든 날짜 필드를 가져올 수 있습니다.

textViewDay.setText(today.monthDay + "");             // Day of the month (1-31)
textViewMonth.setText(today.month + "");              // Month (0-11)
textViewYear.setText(today.year + "");                // Year 
textViewTime.setText(today.format("%k:%M:%S"));  // Current time

모든 세부 사항 android.text.format.Time 클래스를 참조 하십시오.

최신 정보

많은 사람들이 지적했듯이 Google은이 수업에 여러 가지 문제가 있으며 더 이상 사용해서는 안된다고 말합니다.

이 클래스에는 많은 문제가 있으며 대신 GregorianCalendar를 사용하는 것이 좋습니다.

알려진 문제 :

시간 계산을 수행 할 때 역사적인 이유로 현재 모든 산술은 32 비트 정수를 사용하여 수행됩니다. 이것은 1902 년에서 2037 년까지 표현할 수있는 신뢰할 수있는 시간 범위를 제한합니다. 자세한 내용은 2038 년 문제에 대한 위키피디아 기사를 참조하십시오. 이 동작에 의존하지 마십시오. 향후 변경 될 수 있습니다. DST 전환으로 인해 건너 뛴 벽 시간과 같이 존재할 수없는 날짜에 switchTimezone (String)을 호출하면 1969 년 날짜 (즉, 1970 년 1 월 1 일 UTC 1 초 이전 -1 또는 1 초)가됩니다. 대부분의 형식화 / 파싱은 ASCII 텍스트를 가정하므로 비 ASCII 스크립트에 사용하기에 적합하지 않습니다.


현재 날짜 및 시간은 다음을 사용하십시오.

String mydate = java.text.DateFormat.getDateTimeInstance().format(Calendar.getInstance().getTime());

출력되는 내용 :

Feb 27, 2012 5:41:23 PM

이 방법으로 시도 모든 형식이 아래에 제공되어 날짜 및 시간 형식을 가져옵니다.

    Calendar c = Calendar.getInstance();
    SimpleDateFormat dateformat = new SimpleDateFormat("dd-MMM-yyyy hh:mm:ss aa");
    String datetime = dateformat.format(c.getTime());
    System.out.println(datetime);

먼저

둘째 제삼


현재 시간을 확인하려면 System.currentTimeMillis()Java의 표준을 사용할 수 있습니다 . 그런 다음 그것을 사용하여 날짜를 만들 수 있습니다.

Date currentDate = new Date(System.currentTimeMillis());

그리고 다른 사람들이 언급했듯이 시간을 만들려면

Time currentTime = new Time();
currentTime.setToNow();

코드를 사용할 수 있습니다.

Calendar c = Calendar.getInstance();
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String strDate = sdf.format(c.getTime());

산출:

2014-11-11 00:47:55

여기SimpleDateFormat 에서 더 많은 서식 옵션을 얻을 수도 있습니다 .


tl; dr

Instant.now()  // Current moment in UTC.

…또는…

ZonedDateTime.now( ZoneId.of( "America/Montreal" ) )  // In a particular time zone

세부

다른 답변은 정확하지만 구식입니다. 이전 날짜-시간 클래스는 잘못 설계되고 혼란스럽고 번거로운 것으로 입증되었습니다.

java.time

이러한 오래된 클래스는 java.time 프레임 워크 로 대체되었습니다 .

이 새로운 클래스는 JSR 310에 의해 정의되고 ThreeTen-Extra 프로젝트에 의해 확장 매우 성공적인 Joda-Time 프로젝트에서 영감을 받았습니다 .

Oracle Tutorial을 참조하십시오 .

Instant

An Instant최대 나노초의 해상도를 가진 UTC 타임 라인의 한 순간입니다 .

 Instant instant = Instant.now(); // Current moment in UTC.

시간대

표준 시간대 ( ZoneId)를 적용하여 ZonedDateTime. 시간대를 생략하면 JVM의 현재 기본 시간대가 내재적으로 적용됩니다. 원하는 / 예상 시간대를 명시 적으로 지정하는 것이 좋습니다.

사용하여 적절한 시간대 이름 의 형식 continent/region과 같은 America/Montreal, Europe/Brussels또는 Asia/Kolkata. EST또는 IST같은 3-4 자의 약어 는 표준화되거나 고유하지 않으므로 절대 사용하지 마십시오 .

ZoneId zoneId = ZoneId.of( "America/Montreal" ); // Or "Asia/Kolkata", "Europe/Paris", and so on.
ZonedDateTime zdt = ZonedDateTime.ofInstant( instant , zoneId );

Java의 최신 및 레거시 날짜-시간 유형 표

문자열 생성

String날짜-시간 값의 텍스트 표현으로 쉽게 생성 할 수 있습니다 . 표준 형식, 사용자 지정 형식 또는 자동으로 현지화 된 형식을 사용할 수 있습니다.

ISO 8601

toString메서드를 호출하여 일반적이고 합리적인 ISO 8601 표준을 사용하여 텍스트 형식을 지정할 수 있습니다 .

String output = instant.toString();

2016-03-23T03 : 09 : 01.613Z

에 대한 참고 ZonedDateTimetoString방법은 대괄호 시간대의 이름을 추가하여 ISO 8601 표준을 확장합니다. 매우 유용하고 중요한 정보이지만 표준은 아닙니다.

2016-03-22T20 : 09 : 01.613-08 : 00 [America / Los_Angeles]

맞춤 형식

또는 DateTimeFormatter클래스 와 함께 고유 한 특정 형식화 패턴을 지정하십시오 .

DateTimeFormatter formatter = DateTimeFormatter.ofPattern( "dd/MM/yyyy hh:mm a" );

를 지정 Locale인간의 언어 (영어, 대한 프랑스어 등) 일 / 월의 이름을 번역과 또한 연도와 월과 날짜의 순서로 문화적 규범을 정의하는 사용. 참고 Locale시간대과는 아무 상관이 없습니다.

formatter = formatter.withLocale( Locale.US ); // Or Locale.CANADA_FRENCH or such.
String output = zdt.format( formatter );

현지화

더 나은 방법은 java.time이 자동으로 지역화 작업을 수행하도록하는 것입니다.

DateTimeFormatter formatter = DateTimeFormatter.ofLocalizedDateTime( FormatStyle.MEDIUM );
String output = zdt.format( formatter.withLocale( Locale.US ) );  // Or Locale.CANADA_FRENCH and so on.

java.time 정보

Java 및 Android 버전에 사용할 * 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 클래스는 어디서 구할 수 있습니까?

ThreeTen - 추가 프로젝트 추가 클래스와 java.time를 확장합니다. 이 프로젝트는 java.time에 향후 추가 될 수있는 가능성을 입증하는 곳입니다. 당신은 여기에 몇 가지 유용한 클래스와 같은 찾을 수 있습니다 Interval, YearWeek, YearQuarter, 그리고 .


간단합니다. 다음과 같이 시간을 분석하여 현재 시간에 대한 별도의 값을 얻을 수 있습니다.

Calendar cal = Calendar.getInstance(); 

  int millisecond = cal.get(Calendar.MILLISECOND);
  int second = cal.get(Calendar.SECOND);
  int minute = cal.get(Calendar.MINUTE);
        //12 hour format
  int hour = cal.get(Calendar.HOUR);
        //24 hour format
  int hourofday = cal.get(Calendar.HOUR_OF_DAY);

다음과 같이 날짜도 마찬가지입니다.

Calendar cal = Calendar.getInstance(); 

  int dayofyear = cal.get(Calendar.DAY_OF_YEAR);
  int year = cal.get(Calendar.YEAR);
  int dayofweek = cal.get(Calendar.DAY_OF_WEEK);
  int dayofmonth = cal.get(Calendar.DAY_OF_MONTH);

Android는 주로 Java이므로 몇 가지 옵션이 있지만 textView로 작성하려면 다음 코드가 트릭을 수행합니다.

String currentDateTimeString = DateFormat.getDateInstance().format(new Date());

// textView is the TextView view that should display it
textView.setText(currentDateTimeString);

SimpleDateFormat databaseDateTimeFormate = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
SimpleDateFormat databaseDateFormate = new SimpleDateFormat("yyyy-MM-dd");
SimpleDateFormat sdf1 = new SimpleDateFormat("dd.MM.yy");
SimpleDateFormat sdf2 = new SimpleDateFormat("yyyy.MM.dd G 'at' hh:mm:ss z");
SimpleDateFormat sdf3 = new SimpleDateFormat("EEE, MMM d, ''yy");
SimpleDateFormat sdf4 = new SimpleDateFormat("h:mm a");
SimpleDateFormat sdf5 = new SimpleDateFormat("h:mm");
SimpleDateFormat sdf6 = new SimpleDateFormat("H:mm:ss:SSS");
SimpleDateFormat sdf7 = new SimpleDateFormat("K:mm a,z");
SimpleDateFormat sdf8 = new SimpleDateFormat("yyyy.MMMMM.dd GGG hh:mm aaa");


String currentDateandTime = databaseDateTimeFormate.format(new Date());     //2009-06-30 08:29:36
String currentDateandTime = databaseDateFormate.format(new Date());     //2009-06-30
String currentDateandTime = sdf1.format(new Date());     //30.06.09
String currentDateandTime = sdf2.format(new Date());     //2009.06.30 AD at 08:29:36 PDT
String currentDateandTime = sdf3.format(new Date());     //Tue, Jun 30, '09
String currentDateandTime = sdf4.format(new Date());     //8:29 PM
String currentDateandTime = sdf5.format(new Date());     //8:29
String currentDateandTime = sdf6.format(new Date());     //8:28:36:249
String currentDateandTime = sdf7.format(new Date());     //8:29 AM,PDT
String currentDateandTime = sdf8.format(new Date());     //2009.June.30 AD 08:29 AM

날짜 형식 패턴

G   Era designator (before christ, after christ)
y   Year (e.g. 12 or 2012). Use either yy or yyyy.
M   Month in year. Number of M's determine length of format (e.g. MM, MMM or MMMMM)
d   Day in month. Number of d's determine length of format (e.g. d or dd)
h   Hour of day, 1-12 (AM / PM) (normally hh)
H   Hour of day, 0-23 (normally HH)
m   Minute in hour, 0-59 (normally mm)
s   Second in minute, 0-59 (normally ss)
S   Millisecond in second, 0-999 (normally SSS)
E   Day in week (e.g Monday, Tuesday etc.)
D   Day in year (1-366)
F   Day of week in month (e.g. 1st Thursday of December)
w   Week in year (1-53)
W   Week in month (0-5)
a   AM / PM marker
k   Hour in day (1-24, unlike HH's 0-23)
K   Hour in day, AM / PM (0-11)
z   Time Zone

final Calendar c = Calendar.getInstance();
    int mYear = c.get(Calendar.YEAR);
    int mMonth = c.get(Calendar.MONTH);
    int mDay = c.get(Calendar.DAY_OF_MONTH);

textView.setText(""+mDay+"-"+mMonth+"-"+mYear);

이것은 날짜와 시간을 얻는 데 유용한 방법입니다.

private String getDate(){
    DateFormat dfDate = new SimpleDateFormat("yyyy/MM/dd");
    String date=dfDate.format(Calendar.getInstance().getTime());
    DateFormat dfTime = new SimpleDateFormat("HH:mm");
    String time = dfTime.format(Calendar.getInstance().getTime());
    return date + " " + time;
}

이 메서드를 호출하고 현재 날짜 및 시간 값을 가져올 수 있습니다.

2017/01//09 19:23

Time time = new Time();
time.setToNow();
System.out.println("time: " + time.hour+":"+time.minute);

예를 들어 12:32가 표시됩니다.

android.text.format.Time을 가져 오는 것을 잊지 마십시오.


    SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
    Calendar cal = Calendar.getInstance();
    System.out.println("time => " + dateFormat.format(cal.getTime()));

    String time_str = dateFormat.format(cal.getTime());

    String[] s = time_str.split(" ");

    for (int i = 0; i < s.length; i++) {
         System.out.println("date  => " + s[i]);
    }

    int year_sys = Integer.parseInt(s[0].split("/")[0]);
    int month_sys = Integer.parseInt(s[0].split("/")[1]);
    int day_sys = Integer.parseInt(s[0].split("/")[2]);

    int hour_sys = Integer.parseInt(s[1].split(":")[0]);
    int min_sys = Integer.parseInt(s[1].split(":")[1]);

    System.out.println("year_sys  => " + year_sys);
    System.out.println("month_sys  => " + month_sys);
    System.out.println("day_sys  => " + day_sys);

    System.out.println("hour_sys  => " + hour_sys);
    System.out.println("min_sys  => " + min_sys);

android.os.SystemClock을 사용할 수도 있습니다. 예를 들어 SystemClock.elapsedRealtime ()은 전화기가 절전 모드 일 때 더 정확한 시간 판독 값을 제공합니다.


사용자 정의 된 시간 및 날짜 형식 :

    SimpleDateFormat dateFormat= new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZZZZZ",Locale.ENGLISH);
    String cDateTime=dateFormat.format(new Date());

출력은 다음 형식과 같습니다. 2015-06-18T10 : 15 : 56-05 : 00


현재 날짜가 필요하면

Calendar cc = Calendar.getInstance();
int year=cc.get(Calendar.YEAR);
int month=cc.get(Calendar.MONTH);
int mDay = cc.get(Calendar.DAY_OF_MONTH);
System.out.println("Date", year+":"+month+":"+mDay);

현재 시간이 필요하면

 int mHour = cc.get(Calendar.HOUR_OF_DAY);
 int mMinute = cc.get(Calendar.MINUTE);
 System.out.println("time_format"+String.format("%02d:%02d", mHour , mMinute ));

Date todayDate = new Date();
todayDate.getDay();
todayDate.getHours();
todayDate.getMinutes();
todayDate.getMonth();
todayDate.getTime();

Time now = new Time();
now.setToNow();

저에게도 효과가 있습니다.


다음을 사용하여 날짜를 얻을 수 있습니다.

Time t = new Time(Time.getCurrentTimezone());
t.setToNow();
String date = t.format("%Y/%m/%d");

이렇게하면 "2014/02/09"예와 같이 멋진 형식의 결과가 표시됩니다.


형식이있는 현재 날짜 및 시간의 경우

자바에서

Calendar c = Calendar.getInstance();
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String strDate = sdf.format(c.getTime());
Log.d("Date","DATE : " + strDate)

Kotlin에서

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
    val current = LocalDateTime.now()
    val formatter = DateTimeFormatter.ofPattern("dd.MM.yyyy. HH:mm:ss")
    var myDate: String =  current.format(formatter)
    Log.d("Date","DATE : " + myDate)
} else {
    var date = Date()
    val formatter = SimpleDateFormat("MMM dd yyyy HH:mma")
    val myDate: String = formatter.format(date)
    Log.d("Date","DATE : " + myDate)
}

날짜 형식화 패턴

"yyyy.MM.dd G 'at' HH:mm:ss z" ---- 2001.07.04 AD at 12:08:56 PDT
"hh 'o''clock' a, zzzz" ----------- 12 o'clock PM, Pacific Daylight Time
"EEE, d MMM yyyy HH:mm:ss Z"------- Wed, 4 Jul 2001 12:08:56 -0700
"yyyy-MM-dd'T'HH:mm:ss.SSSZ"------- 2001-07-04T12:08:56.235-0700
"yyMMddHHmmssZ"-------------------- 010704120856-0700
"K:mm a, z" ----------------------- 0:08 PM, PDT
"h:mm a" -------------------------- 12:08 PM
"EEE, MMM d, ''yy" ---------------- Wed, Jul 4, '01

다음 코드를 사용하면됩니다.

 DateFormat df = new SimpleDateFormat("HH:mm"); //format time
 String time = df.format(Calendar.getInstance().getTime());

 DateFormat df1=new SimpleDateFormat("yyyy/MM/dd");//foramt date
 String date=df1.format(Calendar.getInstance().getTime());

글쎄요 API의 일부 답변에 문제가 있었기 때문에이 코드를 융합하여 그들에게 도움이되기를 바랍니다.

    Time t = new Time(Time.getCurrentTimezone());
    t.setToNow();
    String date1 = t.format("%Y/%m/%d");

    Date date = new Date(System.currentTimeMillis());
    SimpleDateFormat dateFormat = new SimpleDateFormat("hh:mm aa",
            Locale.ENGLISH);
    String var = dateFormat.format(date);
    String horafecha = var+ " - " + date1;

    tvTime.setText(horafecha);

출력 : 03:25 PM-2017/10/03


아래 메소드는 현재 날짜와 시간을 문자열로 반환하고 실제 시간대에 따라 다른 시간대를 사용합니다.

public static String GetToday(){
    Date presentTime_Date = Calendar.getInstance().getTime();
    SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    dateFormat.setTimeZone(TimeZone.getTimeZone("GMT"));
    return dateFormat.format(presentTime_Date);
}

새로운 API에 따라 Calender 클래스를 사용해야합니다. Date 클래스는 이제 더 이상 사용되지 않습니다.

Calendar cal = Calendar.getInstance();

String date = ""+cal.get(Calendar.DATE)+"-"+(cal.get(Calendar.MONTH)+1)+"-"+cal.get(Calendar.YEAR);

String time = ""+cal.get(Calendar.HOUR_OF_DAY)+":"+cal.get(Calendar.MINUTE);

이 시도

String mytime = (DateFormat.format("dd-MM-yyyy hh:mm:ss", new java.util.Date()).toString());

이 코드를 사용하면 현재 날짜와 시간이 표시됩니다.

 Date date = new Date(System.currentTimeMillis());
 SimpleDateFormat dateFormat = new SimpleDateFormat("hh:mm aa",
                         Locale.ENGLISH);
 String var = dateFormat.format(date));

참고 URL : https://stackoverflow.com/questions/5369682/get-current-time-and-date-on-android

반응형