Android开发:日期格式化

如果有一个Date的变量,需要格式化其数据让显示出来的日期/时间成为我们希望的格式,需要使用到DateFormat类。

如,在一个类Crime中有一个getDate()方法,可以获取日期。这时我们需要使用DateFormat类来进行格式化。

这里提供三个方法来进行格式化:


static CharSequence format(CharSequence inFormat, Calendar inDate)
//Given a format string and a Calendar object, returns a CharSequence containing the requested date.


static CharSequence format(CharSequence inFormat, Date inDate)
//Given a format string and a Date object, returns a CharSequence containing the requested date.


static CharSequence format(CharSequence inFormat, long inTimeInMillis)
//Given a format string and a time in milliseconds since Jan 1, 1970 GMT, returns a CharSequence containing the requested date.

这里要知道,a character sequence is also known as a String!,也就是说charSequence也就是String,因此其返回类型是String。
因为我们现在有一个date类型的变量,因此使用第二个方法,期中第一个参数是一个格式,相关格式对应的日期显示格式会在下面写出来,另外一个参数自然是一个Date;

因此,在开发中,可以有如下解决方法:

 private String getNewDate(Crime userCrime) {
        Date mNewDate;
        mNewDate = mCrime.getDate();

        DateFormat dateFormat = new DateFormat();
        String newDate = dateFormat.format("EEEE, MMMM dd, yyyy h:mmaa", mNewDate).toString();
        return  newDate;
    }

也可以简便一下,如果有一个Button需要显示这个格式化的日期,可以这样:

private Date mNewDate;
.   .   .   
mNewDate = mPatient.getDate();

mDateButton.setText(android.text.format.DateFormat.format("dd-MM-yyy", mNewDate));
mDateButton.setEnabled(false);

这样,日期格式化就解决了。

另外,通过以下的相关的第一个参数设置,可以获得我们需要的日期格式:

For the month of September:
M -> 9
MM -> 09
MMM -> Sep
MMMM -> September

The effects of the duplication vary depending on the nature of the field. See the notes on the individual field formatters for details. For purely numeric fields such as HOUR adding more copies of the designator will zero-pad the value to that number of characters.

For 7 minutes past the hour:
m -> 7
mm -> 07
mmm -> 007
mmmm -> 0007

Examples for April 6, 1970 at 3:23am:
"MM/dd/yy h:mmaa" -> "04/06/70 3:23am"
"MMM dd, yyyy h:mmaa" -> "Apr 6, 1970 3:23am"
"MMMM dd, yyyy h:mmaa" -> "April 6, 1970 3:23am"
"E, MMMM dd, yyyy h:mmaa" -> "Mon, April 6, 1970 3:23am&
"EEEE, MMMM dd, yyyy h:mmaa" -> "Monday, April 6, 1970 3:23am"
"'Noteworthy day: 'M/d/yy" -> "Noteworthy day: 4/6/70"

相关详细内容,可以通过官方文档来查看。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值