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


当前回答

Try:

event.putExtra("startTime", "10/05/2012");

当你访问传递的变量时:

SimpleDateFormat formatter = new SimpleDateFormat("dd/MM/yyyy");
Date date = formatter.parse(bundle.getString("startTime"));

其他回答

在我看来,android.text.format.DateFormat. getdateformat (context)让我感到困惑,因为这个方法返回java.text.DateFormat而不是android.text.format.DateFormat - -"。

因此,我使用下面的片段代码以我的格式获取当前日期/时间。

android.text.format.DateFormat df = new android.text.format.DateFormat();
df.format("yyyy-MM-dd hh:mm:ss a", new java.util.Date());

or

android.text.format.DateFormat.format("yyyy-MM-dd hh:mm:ss a", new java.util.Date());

此外,您还可以使用其他格式。遵循DateFormat。

这是最简单的方法:

    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

这样就可以了:

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

地方

以毫秒格式获取日期或时间,我使用了这个:

日期和时间

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);

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

类型日期

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:(上午/下午)