如何在Android应用程序中获取当前时间和日期?
当前回答
试着用简单的方法获取当前的日期和时间:
SimpleDateFormat sdf = new SimpleDateFormat("yyyy.MM.dd G 'at' HH:mm:ss z");
String currentDateandTime = sdf.format(new Date());
其他回答
下面是一些获取时间和日期的方法:
public static void getCurrentTimeUsingDate() {
Date date = new Date();
String strDateFormat = "hh:mm:ss a";
DateFormat dateFormat = new SimpleDateFormat(strDateFormat);
String formattedDate= dateFormat.format(date);
Toast.makeText(this, formattedDate, Toast.LENGTH_SHORT).show();
}
使用日历的时间
public static void getCurrentTimeUsingCalendar() {
Calendar cal = Calendar.getInstance();
Date date=cal.getTime();
DateFormat dateFormat = new SimpleDateFormat("HH:mm:ss");
String formattedDate=dateFormat.format(date);
Toast.makeText(this, formattedDate, Toast.LENGTH_SHORT).show();
}
当地时间日期
public static void getCurrentTime(){
System.out.println("-----Current time of your time zone-----");
LocalTime time = LocalTime.now();
Toast.makeText(this, time, Toast.LENGTH_SHORT).show();
}
分区时间
public static void getCurrentTimeWithTimeZone(){
Toast.makeText(this, "Current time of a different time zone using LocalTime", Toast.LENGTH_SHORT).show();
ZoneId zoneId = ZoneId.of("America/Los_Angeles");
LocalTime localTime=LocalTime.now(zoneId);
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("HH:mm:ss");
String formattedTime=localTime.format(formatter);
Toast.makeText(this,formattedTime , Toast.LENGTH_SHORT).show();
}
获取当前时间和日期的简单方法
import java.util.Calendar
Date currentTime = Calendar.getInstance().getTime();
Time now = new Time();
now.setToNow();
试试这个对我也有用。
Date todayDate = new Date();
todayDate.getDay();
todayDate.getHours();
todayDate.getMinutes();
todayDate.getMonth();
todayDate.getTime();
你可以使用以下代码:
Calendar c = Calendar.getInstance();
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String strDate = sdf.format(c.getTime());
输出:
2014-11-11 00:47:55
您还可以从这里获得SimpleDateFormat的更多格式化选项。
在com.google.gson.internal.bind.util包中有一个ISO8601Utils实用程序类,所以如果你在你的应用程序中使用Gson,你可以使用它。
它支持毫秒和时区,所以这是一个很好的开箱即用的选择。
推荐文章
- 改变开关的“开”色
- 以编程方式将EditText的输入类型从PASSWORD更改为NORMAL,反之亦然
- 如何在隐藏和查看密码之间切换
- 在Android上调整一个大的位图文件到缩放输出文件
- 如何更改Android版本和代码版本号?
- Android Studio突然无法解析符号
- 应用程序重新启动而不是恢复
- 如何设置整个应用程序在纵向模式?
- 如何减去日期/时间在JavaScript?
- Android中文本的阴影效果?
- 以编程方式设置TextView的布局权重
- Android -如何覆盖“后退”按钮,所以它不完成()我的活动?
- 如何从通知点击发送参数到一个活动?
- 导航目标xxx对于这个NavController是未知的
- 使用ConstraintLayout均匀间距的视图