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


当前回答

最短的方法:

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

其他回答

类型日期

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

现在已经太迟了,但它可能对某人有所帮助

DateFormat.format(format, timeInMillis);

这里是你需要的格式

"HH:mm"返回15:30

使用SimpleDateFormat

是这样的:

event.putExtra("starttime", "12/18/2012");

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

您可以使用DateFormat。结果取决于手机的默认Locale,但你也可以指定Locale:

https://developer.android.com/reference/java/text/DateFormat.html

这是a的结果

DateFormat.getDateInstance().format(date)                                          

地点:2017年11月3日

美国/En当地:Jan 12, 1952


DateFormat.getDateInstance(DateFormat.SHORT).format(date)

地点:03/11/2017

美国和地区:12.13.52


DateFormat.getDateInstance(DateFormat.MEDIUM).format(date)

地点:2017年11月3日

美国/En当地:Jan 12, 1952


DateFormat.getDateInstance(DateFormat.LONG).format(date)

当地时间:2017年11月3日

美国/现场:1952年1月12日


DateFormat.getDateInstance(DateFormat.FULL).format(date)

当地时间:2017年11月3日星期五

美国/现场:1952年4月12日,星期二


DateFormat.getDateTimeInstance().format(date)

FR地点:2017年11月3日16:04:58


DateFormat.getDateTimeInstance(DateFormat.SHORT, DateFormat.SHORT).format(date)

FR地区:03/11/2017 16:04


DateFormat.getDateTimeInstance(DateFormat.SHORT, DateFormat.MEDIUM).format(date)

本地:03/11/2017 16:04:58


DateFormat.getDateTimeInstance(DateFormat.SHORT, DateFormat.LONG).format(date)

本地FR: 03/11/2017 16:04:58 GMT+01:00


DateFormat.getDateTimeInstance(DateFormat.SHORT, DateFormat.FULL).format(date)

当地时间:中欧标准时间03/11/2017 16:04:58


DateFormat.getTimeInstance().format(date)

本地FR: 16:04:58


DateFormat.getTimeInstance(DateFormat.SHORT).format(date)

本地FR: 16:04


DateFormat.getTimeInstance(DateFormat.MEDIUM).format(date)

本地FR: 16:04:58


DateFormat.getTimeInstance(DateFormat.LONG).format(date)

本地FR:格林尼治时间16:04:58 +01:00


DateFormat.getTimeInstance(DateFormat.FULL).format(date)

当地时间:中欧标准时间16:04:58


这是最简单的方法:

    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