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


当前回答

这是最简单的方法:

    SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss a", Locale.US);

    String time = df.format(new Date());

如果你在寻找模式,检查这个 https://docs.oracle.com/javase/7/docs/api/java/text/SimpleDateFormat.html

其他回答

使用标准的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对象。

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

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;

}

日期和时间格式说明

EEE : Day ( Mon )
MMMM : Full month name ( December ) // MMMM February   
MMM : Month in words ( Dec )
MM : Month ( 12 )
dd : Day in 2 chars ( 03 )
d: Day in 1 char (3)
HH : Hours ( 12 )
mm : Minutes ( 50 )
ss : Seconds ( 34 )
yyyy: Year ( 2020 ) //both yyyy and YYYY are same
YYYY: Year ( 2020 )
zzz : GMT+05:30
a : ( AM / PM )
aa : ( AM / PM )
aaa : ( AM / PM )
aaaa : ( AM / PM )

这样就可以了:

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

下面是: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"));