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


当前回答

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

其他回答

使用Time类中的构建!

Time time = new Time();
time.set(0, 0, 17, 4, 5, 1999);
Log.i("DateTime", time.format("%d.%m.%Y %H:%M:%S"));

日期和时间格式说明

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(milliseconds);
DateFormat dateFormat = DateFormat.getDateTimeInstance(DateFormat.MEDIUM, DateFormat.SHORT, Locale.getDefault());
dateFormat.format(date);

Date

Date date = new Date(milliseconds);
DateFormat dateFormat = DateFormat.getDateInstance(DateFormat.MEDIUM, Locale.getDefault());
dateFormat.format(date);

Time

Date date = new Date(milliseconds);
DateFormat dateFormat = DateFormat.getTimeInstance(DateFormat.SHORT, Locale.getDefault());
dateFormat.format(date);

您可以使用其他日期样式和时间样式。更多关于样式的信息。

这段代码将返回当前日期和时间:

public String getCurrDate()
{
    String dt;
    Date cal = Calendar.getInstance().getTime();
    dt = cal.toLocaleString();
    return dt;
}

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

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;

}