Android(安卓)时间获取总结
16lz
2021-12-04
在平时的项目中,获取系统时间的操作是件很普遍的操作,因此,进行总结一下,Android中获取时间主要通过Java中的java.util.Calendar和java,util.Date类来实现,此外android还提供了一个time类也能够实现。
直接通过例子来说明:
package com.hiwhitley.chapter03;import java.sql.Time;import java.text.SimpleDateFormat;import java.util.Calendar;import java.util.Date;public class TimeDemo {public static void main(String[] args) {String date;SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");//Date类Date nowTime = new Date(System.currentTimeMillis()); date = sdf.format(nowTime);System.out.println("date:"+date);//Calendar类Calendar calendar = Calendar.getInstance();date = sdf.format(calendar.getTime());System.out.println("calendar:"+date);//Time类Time time = new Time(System.currentTimeMillis());date = sdf.format(time);System.out.println("time:"+date);}//OutPut://date:2015-11-17 10:41:52//calendar:2015-11-17 10:41:52//time:2015-11-17 10:41:52}
ok,新技能get,就是这么简单,o(∩_∩)o ,剩下可能用到的就是这几个:
1.String和Date的相互转换
//把日期转为字符串 Date==>String public static String ConverToString(Date date) { DateFormat sdf = new SimpleDateFormat("yyyy-MM-dd"); return sdf.format(date); } //把字符串转为日期 String==>Date public static Date ConverToDate(String strDate) throws Exception { DateFormat sdf = new SimpleDateFormat("yyyy-MM-dd"); return sdf.parse(strDate); }
字符串转换为日期时,会抛异常。
2.项目中有可能用到需要得到当前时间的提前几分钟的时间
Calendar calendar = Calendar.getInstance();SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");Date date = new Date(System.currentTimeMillis());calendar.setTime(date);System.out.println("当前时间:"+sdf.format(calendar.getTime()));// 提前15mincalendar.set(Calendar.MINUTE,calendar.get(Calendar.MINUTE) - 15);System.out.println("提前十五分钟的时间:"+sdf.format(calendar.getTime()));//Output//当前时间:2015-11-18 09:42:19//提前十五分钟的时间:2015-11-18 09:27:19
3.SimpleDateFormat类
更多相关文章
- Android(安卓)性能优化案例
- 如何修改Android中Browser的UserAgent
- android 每天定时提醒功能实现
- Android获取CPU使用率的几种方式
- android 每天定时提醒功能实现
- android的PreferenceActivity
- android SystemClock设置系统时间需要system权限
- android开发,你还在犹豫什么呢?进来看看花不了你很多时间的
- android 读取json数据(遍历JSONObject和JSONArray)