如何在Android应用程序中显示当前日期和时间?
当前回答
我自己的工作解决方案:
Calendar c = Calendar.getInstance();
String sDate = c.get(Calendar.YEAR) + "-"
+ c.get(Calendar.MONTH)
+ "-" + c.get(Calendar.DAY_OF_MONTH)
+ " at " + c.get(Calendar.HOUR_OF_DAY)
+ ":" + c.get(Calendar.MINUTE);
希望这能有所帮助!
其他回答
从如何获得完整的日期与正确的格式?:
请使用
android.text.format.DateFormat.getDateFormat(Context context)
android.text.format.DateFormat.getTimeFormat(Context context)
获得当前用户设置意义上的有效时间和日期格式(例如12/24时间格式)。
import android.text.format.DateFormat;
private void some() {
final Calendar t = Calendar.getInstance();
textView.setText(DateFormat.getTimeFormat(this/*Context*/).format(t.getTime()));
}
要获得当前的时间/日期,只需使用以下代码片段:
使用时间:
SimpleDateFormat simpleDateFormatTime = new SimpleDateFormat("HH:mm", Locale.getDefault());
String strTime = simpleDateFormatTime.format(now.getTime());
使用日期:
SimpleDateFormat simpleDateFormatDate = new SimpleDateFormat("E, MMM dd, yyyy", Locale.getDefault());
String strDate = simpleDateFormatDate.format(now.getTime());
这样就可以开始了。
为显示当前日期和时间的Textview
/// For Show Date
String currentDateString = DateFormat.getDateInstance().format(new Date());
// textView is the TextView view that should display it
textViewdate.setText(currentDateString);
/// For Show Time
String currentTimeString = DateFormat.getTimeInstance().format(new Date());
// textView is the TextView view that should display it
textViewtime.setText(currentTimeString);
检查完整的代码Android -显示当前日期和时间在一个Android Studio示例的源代码
如果你想要一行代码:
String date = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(Calendar.getInstance().getTime());
结果是“2016-09-25 16:50:34”
这并不难,因为有几种方法可以做到这一点。我假设你想把当前的日期和时间放入TextView。
String currentDateTimeString = java.text.DateFormat.getDateTimeInstance().format(new Date());
// textView is the TextView view that should display it
textView.setText(currentDateTimeString);
文档中有更多内容,可以在这里轻松找到 . 在那里,您将找到关于如何更改用于转换的格式的更多信息。
推荐文章
- Android Studio, logcat在应用程序关闭后清理
- 在android中从上下文获取活动
- 无法解析主机"<URL here>"没有与主机名关联的地址
- getActivity()在Fragment函数中返回null
- 按钮背景是透明的
- 在Mac OS X上哪里安装Android SDK ?
- 我如何获得图像缩放功能?
- 在Android应用程序中显示当前时间和日期
- 字符串不能识别为有效的日期时间“格式dd/MM/yyyy”
- 如何转换日期时间?将日期时间
- BottomSheetDialogFragment的圆角
- 在应用程序启动时出现“无法获得BatchedBridge,请确保您的bundle被正确打包”的错误
- 我如何改变默认对话框按钮的文本颜色在安卓5
- 更改单选按钮的圆圈颜色
- 如何在android中复制一个文件?