如何在Android应用程序中获取当前时间和日期?
当前回答
你可以用:
import java.util.Calendar;
import java.util.Date;
Date currentTime = Calendar.getInstance().getTime();
Calendar中有许多常量可以满足您的所有需要。
检查Calendar类文档。
其他回答
Time now = new Time();
now.setToNow();
试试这个对我也有用。
//currentTimeMillis is System.currentTimeMillis()
long totalSeconds = currentTimeMillis / 1000;
int currentSecond = (int)totalSeconds % 60;
long totalMinutes = totalSeconds / 60;
int currentMinute = (int)totalMinutes % 60;
long totalHours = totalMinutes / 60;
int currentHour = (int)totalHours % 12;
TextView tvTime = findViewById(R.id.tvTime);
tvTime.setText((currentHour + OR - TIME YOU ARE FROM GMT) + ":" + currentMinute + ":" + currentSecond);
你可以通过这个函数得到你的当地时间和GMT时间
public String getCurrentDate() {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy MMM dd hh:mm a zzz");
Date date = new Date();
sdf.setTimeZone(TimeZone.getTimeZone("GMT+6:00"));
return sdf.format(date);
}
要获取当前时间,您可以使用System.currentTimeMillis(),这是Java中的标准。然后您可以使用它来创建日期
Date currentDate = new Date(System.currentTimeMillis());
正如其他人提到的创造一个时间
Time currentTime = new Time();
currentTime.setToNow();
你可以使用下面的代码获取当前的日期和时间:
val current_data_time= SimpleDateFormat("MMMMddyyyyHHmm", Locale.getDefault())
val currentDateandTime: String = current_data_time.format(Date())
如果你用MMMM:那么月份名称就会显示出来。“3”
如果你用MM:那么数字显示。“3”
Dd表示日,yyyy表示年
如果你只想要最后两位数字,那么yy。
如果你先改变月份和年份,然后需要左右改变MMMM、dd和yyyy,例如:12/3/2021 12:12 dd/MM/ yyyy HH: MM
推荐文章
- 改变开关的“开”色
- 以编程方式将EditText的输入类型从PASSWORD更改为NORMAL,反之亦然
- 如何在隐藏和查看密码之间切换
- 在Android上调整一个大的位图文件到缩放输出文件
- 如何更改Android版本和代码版本号?
- Android Studio突然无法解析符号
- 应用程序重新启动而不是恢复
- 如何设置整个应用程序在纵向模式?
- 如何减去日期/时间在JavaScript?
- Android中文本的阴影效果?
- 以编程方式设置TextView的布局权重
- Android -如何覆盖“后退”按钮,所以它不完成()我的活动?
- 如何从通知点击发送参数到一个活动?
- 导航目标xxx对于这个NavController是未知的
- 使用ConstraintLayout均匀间距的视图