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


当前回答

这样就可以了:

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

其他回答

简单日期格式

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

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

最短的方法:

// 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

这是最简单的方法:

    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

回到2016年,当我想自定义格式(不是根据设备配置,如你所问…)我通常使用字符串资源文件:

在strings.xml:

<string name="myDateFormat"><xliff:g id="myDateFormat">%1$td/%1$tm/%1$tY</xliff:g></string>

在活动:

Log.d(TAG, "my custom date format: "+getString(R.string.myDateFormat, new Date()));

这对于新的日期绑定库的发布也很有用。

我可以在布局文件中有这样的东西:

<TextView
    android:id="@+id/text_release_date"
    android:layout_width="wrap_content"
    android:layout_height="0dp"
    android:layout_weight="1"
    android:padding="2dp"
    android:text="@{@string/myDateFormat(vm.releaseDate)}"
    tools:text="0000"
    />

在java类中:

    MovieDetailViewModel vm = new MovieDetailViewModel();
    vm.setReleaseDate(new Date());