在平时的项目中,获取系统时间的操作是件很普遍的操作,因此,进行总结一下,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类


更多相关文章

  1. Android(安卓)性能优化案例
  2. 如何修改Android中Browser的UserAgent
  3. android 每天定时提醒功能实现
  4. Android获取CPU使用率的几种方式
  5. android 每天定时提醒功能实现
  6. android的PreferenceActivity
  7. android SystemClock设置系统时间需要system权限
  8. android开发,你还在犹豫什么呢?进来看看花不了你很多时间的
  9. android 读取json数据(遍历JSONObject和JSONArray)

随机推荐

  1. Android的framework层音量控制原理分析--
  2. 【android】与pc机进行UDP通信
  3. service详解
  4. android真机测试问题
  5. Android(安卓)软键盘问题总结
  6. Android(安卓)kotlin 记录
  7. 阅读《Android(安卓)从入门到精通》(7)——
  8. 实现简单的Android的播放视频功能
  9. Android(安卓)自定义View及其在布局文件
  10. Android(安卓)解压APK文件