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


当前回答

简单日期格式

我使用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 ...

其他回答

使用这两个作为类变量:

 public java.text.DateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy");
 private Calendar mDate = null;

像这样使用它:

 mDate = Calendar.getInstance();
 mDate.set(year,months,day);                   
 dateFormat.format(mDate.getTime());

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

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

这是最简单的方法:

    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

最短的方法:

// 2019-03-29 16:11
String.format("%1$tY-%<tm-%<td %<tR", Calendar.getInstance())

%tR是%tH:%tM的缩写,<表示重用最后一个参数(1$)。

它等价于String。格式(“% 1 $ tY - % 1 $ tm - td % 1 $ % 1 $ tH: % 1 $ tm”,Calendar.getInstance ())

https://developer.android.com/reference/java/util/Formatter.html