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


当前回答

避免j.u.Date

Java(和Android)中的Java.util. date和. calendar和SimpleDateFormat是出了名的麻烦。避免它们。它们太糟糕了,以至于Sun/Oracle放弃了它们,用新的java取代了它们。Java 8中的time包(2014年Android中没有)。新的java。time的灵感来自Joda-Time图书馆。

乔达时间

Joda-Time在Android上运行。

在StackOverflow上搜索“Joda”可以找到很多例子和很多讨论。

使用Joda-Time 2.4的一小段源代码。

标准格式。

String output = DateTime.now().toString(); 
// Current date-time in user's default time zone with a String representation formatted to the ISO 8601 standard.

本地化的格式。

String output = DateTimeFormat.forStyle( "FF" ).print( DateTime.now() ); 
// Full (long) format localized for this user's language and culture.

其他回答

这段代码将返回当前日期和时间:

public String getCurrDate()
{
    String dt;
    Date cal = Calendar.getInstance().getTime();
    dt = cal.toLocaleString();
    return dt;
}

日期格式类工作与作弊代码,使日期。就像

07, MMM ->七月,MMMM ->七月 EEE ->星期二,EEEE ->星期二 z -> EST, zzz -> EST, zzzz ->东部标准时间

你可以在这里查看更多的作弊。

使用SimpleDateFormat

是这样的:

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

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

地方

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

日期和时间

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

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

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