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


当前回答

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对象。

这样就可以了:

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

android Time类提供了3种格式化方法http://developer.android.com/reference/android/text/format/Time.html

我是这样做的:

/**
* This method will format the data from the android Time class (eg. myTime.setToNow())   into the format
* Date: dd.mm.yy Time: hh.mm.ss
*/
private String formatTime(String time)
{
    String fullTime= "";
    String[] sa = new String[2];

    if(time.length()>1)
    {
        Time t = new Time(Time.getCurrentTimezone());
        t.parse(time);
        // or t.setToNow();
        String formattedTime = t.format("%d.%m.%Y %H.%M.%S");
        int x = 0;

        for(String s : formattedTime.split("\\s",2))
        {   
            System.out.println("Value = " + s);
            sa[x] = s;
            x++;
        }
        fullTime = "Date: " + sa[0] + " Time: " + sa[1];
    }
    else{
        fullTime = "No time data";
    }
    return fullTime;
}

我希望这对你有帮助:-)

这个代码为我工作!

Date d = new Date();
    CharSequence s = android.text.format.DateFormat.format("MM-dd-yy hh-mm-ss",d.getTime());
    Toast.makeText(this,s.toString(),Toast.LENGTH_SHORT).show();

类型日期

EEE:日(星期一) MMMM:完整的月份名称(十二月)// MMMM二月 MMM:文字中的月份(12月) 月(12) dd: 2个字符的天(03) d: 1个字符的天(3) 小时(12) mm:分钟(50) ss:秒(34) yyyy: Year (2022) // yyyy和yyyy相同 年(2022年) zzz: GMT+05:30 a:(上午/下午) aa:(上午/下午) aaa:(上午/下午) aaaa:(上午/下午)