IT

Android에서 현재 날짜를 얻으려면 어떻게해야합니까?

lottoking 2020. 6. 19. 07:56
반응형

Android에서 현재 날짜를 얻으려면 어떻게해야합니까?


다음 코드를 작성했습니다

Date d = new Date();
CharSequence s  = DateFormat.format("MMMM d, yyyy ", d.getTime());

하지만 매개 변수를 묻습니다. 현재 날짜를 문자열 형식으로 원합니다.

처럼

28-Dec-2011

그래서를 통해 설정할 수있는 TextView,

약간의 설명이 필요하다고 생각되면 Android 개발을 처음 사용합니다.


SimpleDateFormat클래스를 사용하여 날짜 형식을 원하는 형식으로 사용할 수 있습니다 .

예제에 대한 아이디어를 얻을 수있는이 링크를 확인하십시오.

예를 들면 다음과 같습니다.

String dateStr = "04/05/2010"; 

SimpleDateFormat curFormater = new SimpleDateFormat("dd/MM/yyyy"); 
Date dateObj = curFormater.parse(dateStr); 
SimpleDateFormat postFormater = new SimpleDateFormat("MMMM dd, yyyy"); 

String newDateStr = postFormater.format(dateObj); 

최신 정보:

자세한 예제는 here입니다 .이 예제를 통해 SimpleDateFormat 클래스의 개념을 이해하는 것이 좋습니다.

마지막 해결책:

Date c = Calendar.getInstance().getTime();
System.out.println("Current time => " + c);

SimpleDateFormat df = new SimpleDateFormat("dd-MMM-yyyy");
String formattedDate = df.format(c);

yyyy-MM-dd 형식으로 현재 날짜를 가져 오는 간단한 한 줄 코드원하는 형식을 사용할 수 있습니다.

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

이것은 자바 기반이므로 안드로이드와 관련이 없으므로 사용할 수 있습니다.

private String getDateTime() { 
   DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
   Date date = new Date(); 
   return dateFormat.format(date); 
}

 public String giveDate() {
    Calendar cal = Calendar.getInstance();
    SimpleDateFormat sdf = new SimpleDateFormat("EEE, MMM d, yyyy");
    return sdf.format(cal.getTime());
 }

이 시도,

SimpleDateFormat timeStampFormat = new SimpleDateFormat("yyyyMMddHHmmssSS");
Date myDate = new Date();
String filename = timeStampFormat.format(myDate);

CharSequence s  = DateFormat.getDateInstance().format("MMMM d, yyyy ");

먼저 인스턴스가 필요합니다


매력처럼 작동하고 보너스로 문자열로 변환합니다.)

SimpleDateFormat currentDate = new SimpleDateFormat("dd/MM/yyyy");
      Date todayDate = new Date();
    String thisDate = currentDate.format(todayDate);

 String date = new SimpleDateFormat("yyyy-MM-dd").format(new Date());

// Date 클래스를 java.util 로 가져 오기


아래 코드는 시간과 날짜를 모두 표시합니다

Calendar cal = Calendar.getInstance();
cal.getTime().toString();

Calendar cal = Calendar.getInstance();      
Calendar dt = Calendar.getInstance(); 
dt.clear();
dt.set(cal.get(Calendar.YEAR), cal.get(Calendar.MONTH),cal.get(Calendar.DATE)); 
return dt.getTime();        

SimpleDateFormat df = new SimpleDateFormat("dd-MMM-yyyy");
String date = df.format(Calendar.getInstance().getTime());

Paresh의 솔루션에 대한 간단한 조정 :

Date date = Calendar.getInstance().getTime();
SimpleDateFormat df = new SimpleDateFormat("dd-MMM-yyyy");
String formattedDate = df.format(date);

다음 코드를 사용하여 원하는 형식으로 날짜를 얻을 수 있습니다.

String date = String.valueOf(android.text.format.DateFormat.format("dd-MM-yyyy", new java.util.Date()));

나는 현대 답변을 제공하고 있습니다.

java.time 및 ThreeTenABP

현재 날짜를 얻으려면

    LocalDate today = LocalDate.now(ZoneId.of("America/Hermosillo"));

이것은 LocalDate프로그램에서 날짜를 유지하기 위해 사용해야 하는 오브젝트를 제공합니다 . A LocalDate는 시간이없는 날짜입니다.

날짜를 사용자에게 표시해야하는 경우에만 사용자의 로캘에 적합한 문자열로 형식을 지정하십시오.

    DateTimeFormatter userFormatter
            = DateTimeFormatter.ofLocalizedDate(FormatStyle.LONG);
    System.out.println(today.format(userFormatter));

이 영어 코드를 오늘 미국 영어 로케일에서 실행했을 때 출력 결과는 다음과 같습니다.

2019 년 7 월 13 일

If you want it shorter, specify FormatStyle.MEDIUM or even FormatStyle.SHORT. DateTimeFormatter.ofLocalizedDate uses the default formatting locale, so the point is that it will give output suitable for that locale, different for different locales.

If your user has very special requirements for the output format, use a format pattern string:

    DateTimeFormatter userFormatter = DateTimeFormatter.ofPattern(
            "d-MMM-u", Locale.forLanguageTag("ar-AE"));

13-يول-2019

I am using and recommending java.time, the modern Java date and time API. DateFormat, SimpleDateFormat, Date and Calendar used in the question and/or many of the other answers, are poorly designed and long outdated. And java.time is so much nicer to work with.

Question: Can I use java.time on Android?

Yes, java.time works nicely on older and newer Android devices. It just requires at least Java 6.

  • In Java 8 and later and on newer Android devices (from API level 26) the modern API comes built-in.
  • In Java 6 and 7 get the ThreeTen Backport, the backport of the modern classes (ThreeTen for JSR 310; see the links at the bottom).
  • On (older) Android use the Android edition of ThreeTen Backport. It’s called ThreeTenABP. And make sure you import the date and time classes from org.threeten.bp with subpackages.

Links


Date c = Calendar.getInstance().getTime();
System.out.println("Current time => " + c);

SimpleDateFormat df = new SimpleDateFormat("dd-MMM-yyyy");
String formattedDate = df.format(c);

This one is the best answer...


Calendar c = Calendar.getInstance();
int day = c.get(Calendar.DAY_OF_MONTH);
int month = c.get(Calendar.MONTH);
int year = c.get(Calendar.YEAR);
String date = day + "/" + (month + 1) + "/" + year;

Log.i("TAG", "--->" + date);

 public static String getcurrentDateAndTime(){

        Date c = Calendar.getInstance().getTime();
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy/MM/dd");
        String formattedDate = simpleDateFormat.format(c);
        return formattedDate;
    }

// String currentdate=  getcurrentDateAndTime();

The simplest way to get the current date in current locale (device locale!) :

String currentDate = DateFormat.getDateInstance().format(Calendar.getInstance().getTime());

If you want to have the date in different styles use getDateInstance(int style):

DateFormat.getDateInstance(DateFormat.FULL).format(Calendar.getInstance().getTime());

Other styles: DateFormat.LONG, DateFormat.DATE_FIELD, DateFormat.DAY_OF_YEAR_FIELD, etc. (use CTRL+Space to see all of them)

If you need the time too:

String currentDateTime = DateFormat.getDateTimeInstance(DateFormat.DEFAULT,DateFormat.LONG).format(Calendar.getInstance().getTime());

  public static String getDateTime() {
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("MMMM dd, yyyy HH:mm:ss", Locale.getDefault());
        Date date = new Date();
        return simpleDateFormat.format(date);
    }

try with this link of code this is absolute correct answer for all cases all over date and time. or customize date and time as per need and requirement of app.

try with this link .try with this link


I wrote calendar app using CalendarView and it's my code:

CalendarView cal = (CalendarView) findViewById(R.id.calendar);
cal.setDate(new Date().getTime());

'calendar' field is my CalendarView. Imports:

import android.widget.CalendarView;
import java.util.Date;

I've got current date without errors.


This is the code i used:

             Date date = new Date();  // to get the date
             SimpleDateFormat df = new SimpleDateFormat("dd-MM-yyyy"); // getting date in this format
             String formattedDate = df.format(date.getTime());
             text.setText(formattedDate);

I've already used this:

Date What_Is_Today=Calendar.getInstance().getTime();
SimpleDateFormat Dateformat = new SimpleDateFormat("dd-MM-yyyy");
String Today=Dateformatf.format(What_Is_Today);

Toast.makeText(this,Today,Toast.LENGTH_LONG).show();

at first I get time, then I declared a Simple Date Format (to get date like: 19-6-2018) then I use format to change date to string.


This is the code I used:

final Calendar c = Calendar.getInstance();
year = c.get(Calendar.YEAR);
month = c.get(Calendar.MONTH);
day = c.get(Calendar.DAY_OF_MONTH);

// Set current date into textview
tvDisplayDate.setText(new StringBuilder()
    .append(month + 1).append("-") // Month is 0 based, add 1
    .append(day).append("-")
    .append(year).append("   Today is :" + thursday ) );

// Set current date into datepicker
dpResult.init(year, month, day, null);

참고URL : https://stackoverflow.com/questions/8654990/how-can-i-get-current-date-in-android

반응형