在有年、月、日、时、分的情况下,如何根据设备配置的日期和时间正确格式化?


当前回答

在我看来,android.text.format.DateFormat. getdateformat (context)让我感到困惑,因为这个方法返回java.text.DateFormat而不是android.text.format.DateFormat - -"。

因此,我使用下面的片段代码以我的格式获取当前日期/时间。

android.text.format.DateFormat df = new android.text.format.DateFormat();
df.format("yyyy-MM-dd hh:mm:ss a", new java.util.Date());

or

android.text.format.DateFormat.format("yyyy-MM-dd hh:mm:ss a", new java.util.Date());

此外,您还可以使用其他格式。遵循DateFormat。

其他回答

简单日期格式

我使用SimpleDateFormat没有自定义模式,以设备的预选格式从系统中获得实际的日期和时间:

public static String getFormattedDate() {
    //SimpleDateFormat called without pattern
    return new SimpleDateFormat().format(Calendar.getInstance().getTime());
}

返回:

13.01.15 11 1/13/15上午10:45 ...

下面是:http://developer.android.com/reference/android/text/format/Time.html

最好使用Android原生的Time类:

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

然后格式:

Log.d("DEBUG", "Time "+now.format("%d.%m.%Y %H.%M.%S"));

这是我的方法,可以定义和输入输出格式。

public static String formattedDateFromString(String inputFormat, String outputFormat, String inputDate){
    if(inputFormat.equals("")){ // if inputFormat = "", set a default input format.
        inputFormat = "yyyy-MM-dd hh:mm:ss";
    }
    if(outputFormat.equals("")){
        outputFormat = "EEEE d 'de' MMMM 'del' yyyy"; // if inputFormat = "", set a default output format.
    }
    Date parsed = null;
    String outputDate = "";

    SimpleDateFormat df_input = new SimpleDateFormat(inputFormat, java.util.Locale.getDefault());
    SimpleDateFormat df_output = new SimpleDateFormat(outputFormat, java.util.Locale.getDefault());

    // You can set a different Locale, This example set a locale of Country Mexico.
    //SimpleDateFormat df_input = new SimpleDateFormat(inputFormat, new Locale("es", "MX"));
    //SimpleDateFormat df_output = new SimpleDateFormat(outputFormat, new Locale("es", "MX"));

    try {
        parsed = df_input.parse(inputDate);
        outputDate = df_output.format(parsed);
    } catch (Exception e) { 
        Log.e("formattedDateFromString", "Exception in formateDateFromstring(): " + e.getMessage());
    }
    return outputDate;

}

Date to Locale日期字符串:

Date date = new Date();
String stringDate = DateFormat.getDateTimeInstance().format(date);

选项:

   DateFormat.getDateInstance() 

- > 1969年12月31日

   DateFormat.getDateTimeInstance() 

-> 1969年12月31日下午4:00:00

   DateFormat.getTimeInstance() 

->下午4:00:00

使用标准的Java DateFormat类。

例如,要显示当前的日期和时间,请执行以下操作:

Date date = new Date(location.getTime());
DateFormat dateFormat = android.text.format.DateFormat.getDateFormat(getApplicationContext());
mTimeText.setText("Time: " + dateFormat.format(date));

你可以用你自己的值初始化一个Date对象,但是你应该知道构造函数已经被弃用了,你应该真正使用一个Java Calendar对象。