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


当前回答

使用Time类中的构建!

Time time = new Time();
time.set(0, 0, 17, 4, 5, 1999);
Log.i("DateTime", time.format("%d.%m.%Y %H:%M:%S"));

其他回答

Try:

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

当你访问传递的变量时:

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

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

DateFormat.format(format, timeInMillis);

这里是你需要的格式

"HH:mm"返回15:30

这样就可以了:

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

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

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

避免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.