Android 系统时间获取,与计算

筅森魡賤 提交于 2019-11-30 03:35:17

Android 系统时间获取,与计算

获取字符型时间

SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy年MM月dd日 HH:mm:ss");// HH:mm:ss
//获取当前时间
Date date = new Date(System.currentTimeMillis());//毫秒值
time1.setText("Date获取当前日期时间"+simpleDateFormat.format(date));

这里的时间格式可以动态的更具里的需求来写。
比如这样是可行的

SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");

获取数据型时间

Calendar calendar = Calendar.getInstance();
        //获取系统的日期
        //年
        int year = calendar.get(Calendar.YEAR);
        //月
        int month = calendar.get(Calendar.MONTH)+1;
        //日
        int day = calendar.get(Calendar.DAY_OF_MONTH);
        //小时
        int hour = calendar.get(Calendar.HOUR_OF_DAY);
        //分钟
        int minute = calendar.get(Calendar.MINUTE);
        //秒
        int second = calendar.get(Calendar.SECOND);
       // 周 weekday
        int week = calendar.get(Calendar.DAY_OF_WEEK);

注意:月份是需要+1的。对于时间有24小时和12小时制。星期返回的是一个int值。需要自己进行转换。

字符串转时间

 public static int timeCompare(String startTime, String endTime) {
        int i = 0;
        //注意:传过来的时间格式必须要和这里填入的时间格式相同
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm");
        try {
            Date date1 = dateFormat.parse(startTime);//开始时间
            Date date2 = dateFormat.parse(endTime);//结束时间
            // 1 结束时间小于开始时间 2 开始时间与结束时间相同 3 结束时间大于开始时间
            if (date2.getTime() < date1.getTime()) {
                //结束时间小于开始时间
                i = 1;
            } else if (date2.getTime() == date1.getTime()) {
                //开始时间与结束时间相同
                i = 2;
            } else if (date2.getTime() > date1.getTime()) {
                //结束时间大于开始时间
                i = 3;
            }
        } catch (Exception e) {
        }
        return i;
    }

转载于

时间的计算

计算相差多少分钟,相差多少天,天数增加

 SimpleDateFormat f = new SimpleDateFormat("yyyy-MM-dd");
 
        Date today = new Date();
        System.out.println("今天是:" + f.format(today));
 
        Calendar c = Calendar.getInstance();
        c.setTime(today);
        c.add(Calendar.DAY_OF_MONTH, 1);// 今天+1天
 
        Date tomorrow = c.getTime();
        System.out.println("明天是:" + f.format(tomorrow));

相差天数的计算

public static void main(String[] args) throws ParseException {
String s1="2016-1-2";
String s2="2016-1-1";
DateFormat df=new SimpleDateFormat("yyyy-MM-dd");
Calendar calendar=new GregorianCalendar();
Date d1=df.parse(s1);
Date d2=df.parse(s2);
System.out.println((d1.getTime()-d2.getTime())/(60*60*1000*24));
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!