格式化日历日期

sca*_*and 32 formatting android calendar date

我只想让日期显示如下:

Saturday, May 26, 2012 at 10:42 PM

到目前为止,这是我的代码:

Calendar calendar = Calendar.getInstance();
String theDate = calendar.get(Calendar.MONTH) + " " + calendar.get(Calendar.DAY_OF_MONTH) + " " + calendar.get(Calendar.YEAR);

lastclick.setText(getString(R.string.lastclick) + " " + theDate);
Run Code Online (Sandbox Code Playgroud)

这显示了月,日和年的数字,但必须有更好的方法吗?是不是有一些简单的方法来做这个就像使用PHP的date()功能?

cre*_*ama 97

Calendar calendar = Calendar.getInstance();
SimpleDateFormat format = new SimpleDateFormat("EEEE, MMMM d, yyyy 'at' h:mm a");
System.out.println(format.format(calendar.getTime()));
Run Code Online (Sandbox Code Playgroud)

运行上面的代码输出当前时间(例如Saturday, May 26, 2012 at 11:03 PM).

有关更多信息,请参阅Android文档SimpleDateFormat.

格式规范SimpleDateFormat类似于PHP的date功能:

echo date("l, M j, Y \a\\t g:i A");
Run Code Online (Sandbox Code Playgroud)

你是对的.与Java代码相比,PHP代码更加简洁.


Sha*_*wal 16

根据需要使用以下格式化日期.请参阅此链接

 Calendar calendar = Calendar.getInstance();
 lastclick.setText(getString(R.string.lastclick) + " " + String.format("%1$tA %1$tb %1$td %1$tY at %1$tI:%1$tM %1$Tp", calendar));
Run Code Online (Sandbox Code Playgroud)

其中%1 $ tA为staurday,%1 $ tb为5月,

等等...

  • 我无意中投票了这一票,但我似乎无法不降低票数就删除我的投票,这是没有必要的。此方法有效,但是下面的方法更简单易读。 (2认同)

Str*_*ing 13

这实际上是一个相当微妙的问题,而且我没有在SO上看到另一个解决这两个问题的答案:

  • 所述Calendar的时间段(这意味着其可能呈现出不同的日期比本地)
  • 设备Locale(影响日期格式的"正确"方式)

此问题的先前答案忽略了区域设置,以及涉及转换为Date忽略时区的其他答案.所以这是一个更完整,通用的解决方案:

Calendar cal = Calendar.getInstance(); // the value to be formatted
java.text.DateFormat formatter = java.text.DateFormat.getDateInstance(
        java.text.DateFormat.LONG); // one of SHORT, MEDIUM, LONG, FULL, or DEFAULT
formatter.setTimeZone(cal.getTimeZone());
String formatted = formatter.format(cal.getTime());
Run Code Online (Sandbox Code Playgroud)

请注意,您需要在java.text.DateFormat这里使用,而不是Android自己(令人困惑的名字)android.text.format.DateFormat.