programing

Android에서 현재 시간 및 날짜를 가져오는 방법

starjava 2023. 6. 1. 21:39
반응형

Android에서 현재 시간 및 날짜를 가져오는 방법

안드로이드 앱에서 현재 시간과 날짜를 얻으려면 어떻게 해야 합니까?

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

import java.util.Calendar;
import java.util.Date;

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

달력에는 필요한 모든 항목에 대한 많은 상수가 있습니다.

일정관리 클래스 문서를 확인합니다.

Android.text.format을 사용할 수 있습니다(그러나이상 아래를 참조하면 안 됩니다!).시간:

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

위에 링크된 참조에서:

시간 클래스는 java.util의 빠른 대체입니다.달력 및 java.util.그레고리력 클래스.시간 클래스의 인스턴스는 두 번째 정밀도로 지정된 시간의 순간을 나타냅니다.


참고 1: 이 답변을 작성한 지 몇 년이 지났으며, 이 답변은 오래된 Android 전용 클래스에 대한 것입니다.Google은 이제 "이 클래스에는 여러 가지 문제가 있으며 대신 그레고리력을 사용하는 것이 좋습니다."라고 말합니다.


참고 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());

다음과 같은 날짜 형식 패턴을 사용할 수 있습니다.

"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을 참조하십시오.모든 세부 정보에 대한 시간 클래스입니다.

갱신하다

많은 사람들이 지적하고 있듯이, 구글은 이 클래스에 여러 가지 문제가 있으며 더 이상 사용해서는 안 된다고 말합니다.

이 클래스에는 여러 가지 문제가 있으며 대신 그레고리력을 사용하는 것이 좋습니다.

알려진 문제:

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

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 튜토리얼을 참조하십시오.

Instant

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

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

표준 시간대

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

올바른 표준시 이름을 다음 형식으로 사용합니다.continent/region, , , , , 와 같은 3-4 문자의 약어를 사용하지 마십시오.EST또는IST표준화되지도 않고 고유하지도 않기 때문입니다.

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

의 경우:ZonedDateTime,toStringmethod는 표준 시간대의 이름을 대괄호 안에 추가하여 ISO 8601 표준을 확장합니다.매우 유용하고 중요한 정보이지만 표준 정보는 아닙니다.

2016-03-22T 20:09:01.613-08:00[미국/로스앤젤레스]

사용자 지정 형식

또는 클래스를 사용하여 고유한 형식 지정 패턴을 지정합니다.

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

일/월 이름을 번역할 때 사용할 사용자 언어(영어, 프랑스어 등)에 대한 a를 지정하고 연도, 월, 날짜 등의 문화적 표준을 정의할 때도 지정합니다.참고: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.time 프레임워크는 Java 8 이상에 내장되어 있습니다.이러한 클래스는 , , 및 와 같은 문제가 있는 오래된 기존 날짜/시간 클래스를 대체합니다.

자세한 내용은 오라클 튜토리얼을 참조하십시오.그리고 스택 오버플로를 검색하여 많은 예와 설명을 찾습니다.사양은 JSR 310입니다.

현재 유지보수 모드에 있는 Joda-Time 프로젝트는 java.time 클래스로 마이그레이션할 것을 권장합니다.

java.time 개체를 데이터베이스와 직접 교환할 수 있습니다.JDBC 4.2 이상을 준수하는 JDBC 드라이버를 사용합니다.문자열이 필요하지 않고, 필요하지 않습니다.java.sql.*반.최대 절전 모드 5 및 JPA 2.2는 java.time을 지원합니다.

java.time 클래스는 어디에서 얻을 수 있습니까?

Java 및 Android 버전에서 사용할 java.time 기술의 구현을 나열하는 표입니다.

현재 날짜 및 시간에 대해 다음을 사용합니다.

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여기서부터

쉬운 방법입니다. 다음과 같이 시간을 해부하여 현재 시간에 대한 별도의 값을 얻을 수 있습니다.

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);
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

형식이 포함된 현재 날짜 및 시간에 대해 다음을 사용합니다.

자바에서

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)

인 코틀린

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
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

현재 날짜가 필요한 경우:

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));

Android.os도 사용할 수 있습니다.시스템 시계.예를 들어 SystemClock.elped Realtime()은 전화기가 절전 모드일 때 보다 정확한 시간 판독치를 제공합니다.

    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);

사용:

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

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

말고 기억하세요import android.text.format.Time;.

다음 코드를 간단히 사용할 수 있습니다.

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

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

Android의 현재 시간 및 날짜(형식

Calendar c = Calendar.getInstance();
System.out.println("Current dateTime => " + c.getTime());
SimpleDateFormat df = new SimpleDateFormat("dd-MM-yyyy HH:mm:ss a");
String formattedDate = df.format(c.getTime());
System.out.println("Format dateTime => " + formattedDate);

산출량

I/System.out: Current dateTime => Wed Feb 26 02:58:17 GMT+05:30 2020
I/System.out: Format dateTime => 26-02-2020 02:58:17 AM

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

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

출력 형식은 다음과 같습니다.

2015-06-18T 10:15:56-05:00

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

저도 이것을 사용해 보세요.

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

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

이렇게 하면 "2014/02/09"와 같은 멋진 형식의 결과를 얻을 수 있습니다.

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

자바

Long date=System.currentTimeMillis();
SimpleDateFormat dateFormat =new SimpleDateFormat("dd / MMMM / yyyy - HH:mm", Locale.getDefault());
String dateStr = dateFormat.format(date);

코틀린

날짜 if 밀리초 및 13자리(16진수부터 현재까지)

val date=System.currentTimeMillis() //here the date comes in 13 digits
val dtlong = Date(date)
val sdfdate = SimpleDateFormat(pattern, Locale.getDefault()).format(dtlong)

날짜 포맷터

"dd / MMMM / yyyy - HH:mm" -> 29 / April / 2022 - 12:03 
"dd / MM / yyyy" -> 29 / 03 / 2022
"dd / MMM / yyyy" -> 29 / Mar / 2022 (shortens the month) 
"EEE, d MMM yyyy HH:mm:ss" -> Wed, 4 Jul 2022 12:08:56
Date todayDate = new Date();
todayDate.getDay();
todayDate.getHours();
todayDate.getMinutes();
todayDate.getMonth();
todayDate.getTime();

사용해 보십시오.

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

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

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);

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

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);
}

언급URL : https://stackoverflow.com/questions/5369682/how-to-get-current-time-and-date-in-android

반응형