Android 응용 프로그램에서 현재 시간 및 날짜 표시
안드로이드 애플리케이션에서 현재 날짜와 시간을 표시하려면 어떻게 해야 합니까?
좋아요, 그렇게 어렵지는 않아요. 여러 가지 방법이 있기 때문입니다.현재 날짜와 시간을 입력하고 싶은 것 같습니다.TextView.
String currentDateTimeString = java.text.DateFormat.getDateTimeInstance().format(new Date());
// textView is the TextView view that should display it
textView.setText(currentDateTimeString);
설명서에는 여기에서 쉽게 찾을 수 있는 읽을 거리가 더 있습니다.변환에 사용되는 형식을 변경하는 방법에 대한 자세한 내용은 여기에서 확인할 수 있습니다.
public class XYZ extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//setContentView(R.layout.main);
Calendar c = Calendar.getInstance();
System.out.println("Current time => "+c.getTime());
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String formattedDate = df.format(c.getTime());
// formattedDate have current date/time
Toast.makeText(this, formattedDate, Toast.LENGTH_SHORT).show();
// Now we display formattedDate value in TextView
TextView txtView = new TextView(this);
txtView.setText("Current Date and Time : "+formattedDate);
txtView.setGravity(Gravity.CENTER);
txtView.setTextSize(20);
setContentView(txtView);
}
}

public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Thread myThread = null;
Runnable runnable = new CountDownRunner();
myThread= new Thread(runnable);
myThread.start();
}
public void doWork() {
runOnUiThread(new Runnable() {
public void run() {
try{
TextView txtCurrentTime= (TextView)findViewById(R.id.lbltime);
Date dt = new Date();
int hours = dt.getHours();
int minutes = dt.getMinutes();
int seconds = dt.getSeconds();
String curTime = hours + ":" + minutes + ":" + seconds;
txtCurrentTime.setText(curTime);
}catch (Exception e) {}
}
});
}
class CountDownRunner implements Runnable{
// @Override
public void run() {
while(!Thread.currentThread().isInterrupted()){
try {
doWork();
Thread.sleep(1000);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}catch(Exception e){
}
}
}
}
시간을 표시하기 위한 분명한 선택은 보기와 보기입니다.
예를 들어, 다음 레이아웃이 있습니다.
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical">
<AnalogClock
android:layout_width="fill_parent"
android:layout_height="wrap_content"/>
<DigitalClock
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:textSize="20sp"/>
</LinearLayout>
다음과 같이 표시됩니다.

코드 한 줄을 원하는 경우:
String date = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(Calendar.getInstance().getTime());
결과는"2016-09-25 16:50:34"
나만의 해결책:
Calendar c = Calendar.getInstance();
String sDate = c.get(Calendar.YEAR) + "-"
+ c.get(Calendar.MONTH)
+ "-" + c.get(Calendar.DAY_OF_MONTH)
+ " at " + c.get(Calendar.HOUR_OF_DAY)
+ ":" + c.get(Calendar.MINUTE);
이것이 도움이 되길 바랍니다!
사용할 수 있는 특정 패턴의 날짜 및 시간을 원하는 경우
Date d = new Date();
CharSequence s = DateFormat.format("yyyy-MM-dd hh:mm:ss", d.getTime());
올바른 형식으로 전체 날짜를 얻는 방법:
사용하십시오.
android.text.format.DateFormat.getDateFormat(Context context)
android.text.format.DateFormat.getTimeFormat(Context context)
현재 사용자 설정에서 유효한 시간 및 날짜 형식(예: 12/24 시간 형식)을 가져옵니다.
import android.text.format.DateFormat;
private void some() {
final Calendar t = Calendar.getInstance();
textView.setText(DateFormat.getTimeFormat(this/*Context*/).format(t.getTime()));
}
여기 저에게 효과가 있었던 코드가 있습니다.이것 좀 드셔보세요.시스템 호출에서 시간과 날짜가 걸리는 간단한 방법입니다.
public static String getDatetime() {
Calendar c = Calendar .getInstance();
System.out.println("Current time => "+c.getTime());
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mms");
String formattedDate = df.format(c.getTime());
return formattedDate;
}
사용:
Calendar c = Calendar.getInstance();
int seconds = c.get(Calendar.SECOND);
int minutes = c.get(Calendar.MINUTE);
int hour = c.get(Calendar.HOUR);
String time = hour + ":" + minutes + ":" + seconds;
int day = c.get(Calendar.DAY_OF_MONTH);
int month = c.get(Calendar.MONTH);
int year = c.get(Calendar.YEAR);
String date = day + "/" + month + "/" + year;
// Assuming that you need date and time in a separate
// textview named txt_date and txt_time.
txt_date.setText(date);
txt_time.setText(time);
String formattedDate = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(Calendar.getInstance().getTime());
사용하다formattedDate당신과 마찬가지로String날짜가 꽉 찬
내 경우:mDateButton.setText(formattedDate);
사실, 당신은 텍스트 시계 위젯을 사용하는 것이 가장 좋습니다.사용자를 위해 모든 복잡성을 처리하고 사용자의 12/24시간 기본 설정을 준수합니다.http://developer.android.com/reference/android/widget/TextClock.html
현재 날짜 함수를 표시하는 방법
Calendar c = Calendar.getInstance();
SimpleDateFormat df = new SimpleDateFormat("dd-MMM-yyyy");
String date = df.format(c.getTime());
Date.setText(date);
가져오기를 원할 것
java.text를 가져옵니다.SimpleDateFormat.java.util을 가져옵니다.달력;
사용해야 합니다.
TextView Date;
Date = (TextView) findViewById(R.id.Date);
Calendar c = Calendar.getInstance();
int month=c.get(Calendar.MONTH)+1;
String sDate = c.get(Calendar.YEAR) + "-" + month+ "-" + c.get(Calendar.DAY_OF_MONTH) +
"T" + c.get(Calendar.HOUR_OF_DAY)+":"+c.get(Calendar.MINUTE)+":"+c.get(Calendar.SECOND);
그러면 2010-05-24T 18:13:00과 같은 날짜 시간 형식이 제공됩니다.
그러면 현재 날짜와 시간이 표시됩니다.
public String getCurrDate()
{
String dt;
Date cal = Calendar.getInstance().getTime();
dt = cal.toLocaleString();
return dt;
}
이 코드를 복사하고 이 코드가 잘 작동하기를 바랍니다.
Calendar c = Calendar.getInstance();
SimpleDateFormat sdf = new SimpleDateFormat("dd:MMMM:yyyy HH:mm:ss a");
String strDate = sdf.format(c.getTime());
String currentDateandTime = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date());
Toast.makeText(getApplicationContext(), currentDateandTime, Toast.LENGTH_SHORT).show();
다음 코드를 사용해 보십시오.
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);
이 방법으로 시도할 수 있습니다.
Calendar calendar = Calendar.getInstance();
SimpleDateFormat mdformat = new SimpleDateFormat("HH:mm:ss");
String strDate = "Current Time : " + mdformat.format(calendar.getTime());
안드로이드에서 날짜/시간으로 작업하고 싶다면 ThreeTen을 사용하는 것을 추천합니다.의 버전인 ABPjava.time.*패키지(안드로이드의 API 26에서 시작하여 사용 가능) 대체품으로 Java 8과 함께 제공됨java.util.Date그리고.java.util.Calendar.
LocalDate localDate = LocalDate.now();
DateTimeFormatter formatter = DateTimeFormatter.ofLocalizedDate(FormatStyle.MEDIUM);
String date = localDate.format(formatter);
textView.setText(date);
텍스트 보기에 현재 날짜 및 시간 표시
/// For Show Date
String currentDateString = DateFormat.getDateInstance().format(new Date());
// textView is the TextView view that should display it
textViewdate.setText(currentDateString);
/// For Show Time
String currentTimeString = DateFormat.getTimeInstance().format(new Date());
// textView is the TextView view that should display it
textViewtime.setText(currentTimeString);
Android 전체 코드 확인 – Android Studio에서 현재 날짜와 시간 표시 예제(소스 코드 포함)
현재 시간/날짜를 가져오려면 다음 코드 스니펫을 사용하십시오.
시간 사용하기:
SimpleDateFormat simpleDateFormatTime = new SimpleDateFormat("HH:mm", Locale.getDefault());
String strTime = simpleDateFormatTime.format(now.getTime());
날짜 사용하기:
SimpleDateFormat simpleDateFormatDate = new SimpleDateFormat("E, MMM dd, yyyy", Locale.getDefault());
String strDate = simpleDateFormatDate.format(now.getTime());
그리고 당신은 가도 좋습니다.
SimpleDateFormat format = new SimpleDateFormat("dd/MM/yyyy");
Calendar c = Calendar.getInstance();
Date date = Calendar.getInstance().getTime();
String sDate = format.format(date);//31-12-9999
int mYear = c.get(Calendar.YEAR);//9999
int mMonth = c.get(Calendar.MONTH);
mMonth = mMonth + 1;//12
int hrs = c.get(Calendar.HOUR_OF_DAY);//24
int min = c.get(Calendar.MINUTE);//59
String AMPM;
if (c.get(Calendar.AM_PM) == 0) {
AMPM = "AM";
} else {
AMPM = "PM";
}
언급URL : https://stackoverflow.com/questions/2271131/display-the-current-time-and-date-in-an-android-application
'programing' 카테고리의 다른 글
| NSNumber를 사용하여 통화 입력 형식 지정스위프트의 포맷터 (0) | 2023.07.30 |
|---|---|
| 부트스트랩 4의 class="mb-0"은 무엇입니까? (0) | 2023.07.30 |
| T-SQL(SQL Server)에서 "Duplicate Key" 오류를 무시하는 방법 (0) | 2023.07.30 |
| 요구사항에 적합한 첫 번째 줄을 삭제하는 방법은 무엇입니까?MySQL(MariaDB) (0) | 2023.07.30 |
| Numpy 배열에 새로운 차원을 추가하려면 어떻게 해야 합니까? (0) | 2023.07.10 |