如何在Android应用程序中获取当前时间和日期?
当前回答
Use:
Time time = new Time();
time.setToNow();
System.out.println("time: " + time.hour + ":" + time.minute);
例如,这将为您提供“12:32”。
记得导入android.text.format.Time;。
其他回答
如果你想以特定的模式获取日期和时间,你可以使用以下命令:
SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd_HHmmss", Locale.getDefault());
String currentDateandTime = sdf.format(new Date());
Or,
日期:
String currentDate = new SimpleDateFormat("dd-MM-yyyy", Locale.getDefault()).format(new Date());
时间:
String currentTime = new SimpleDateFormat("HH:mm:ss", Locale.getDefault()).format(new Date());
Date todayDate = new Date();
todayDate.getDay();
todayDate.getHours();
todayDate.getMinutes();
todayDate.getMonth();
todayDate.getTime();
试试这段代码。它显示当前的日期和时间。
Date date = new Date(System.currentTimeMillis());
SimpleDateFormat dateFormat = new SimpleDateFormat("hh:mm aa",
Locale.ENGLISH);
String var = dateFormat.format(date));
下面的方法将以字符串形式返回当前日期和时间,请根据您的实际时区使用不同的时区。我用的是格林尼治时间。
public static String GetToday(){
Date presentTime_Date = Calendar.getInstance().getTime();
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
dateFormat.setTimeZone(TimeZone.getTimeZone("GMT"));
return dateFormat.format(presentTime_Date);
}
您可以从日历中单独获取时间和日期。
// You can pass time zone and Local to getInstance() as parameter
Calendar calendar = Calendar.getInstance();
int currentHour = calendar.get(Calendar.HOUR_OF_DAY);
int currentMinute = calendar.get(Calendar.MINUTE);
int second = calendar.get(Calendar.SECOND);
int date = calendar.get(Calendar.DAY_OF_MONTH);
int month = calendar.get(Calendar.MONTH);
int year = calendar.get(Calendar.YEAR);
推荐文章
- 在Android 5棒棒糖中,通知栏图标变成白色
- 从URI获取真实路径,Android奇巧新的存储访问框架
- 如何检查JSON键是否存在?
- ImageView -有高度匹配宽度?
- 如何确定在android文件的MIME类型?
- 这是在Android中获取用户位置的好方法
- Android从左到右幻灯片动画
- MySQL中两个日期之间的差异
- 如何检索视图的维度?
- 如何改变菜单项的文本颜色在安卓?
- 在Bash中获取日期(比当前时间早一天)
- Android选择器和文本颜色
- 视图绑定-我如何获得包含布局的绑定?
- 在Android Studio中改变矢量资产的填充颜色
- 在构建中编写注释的语法是什么?gradle文件?