2018-11-30 15:31:33 sp_wei 阅读数 1216

1.使用calendar类实现

/** 
 * 取得当月天数 
 * */  
public static int getCurrentMonthLastDay()  
{  
    Calendar a = Calendar.getInstance();  
    a.set(Calendar.DATE, 1);//把日期设置为当月第一天  
    a.roll(Calendar.DATE, -1);//日期回滚一天,也就是最后一天  
    int maxDate = a.get(Calendar.DATE);  
    return maxDate;  
}  
  
/** 
 * 得到指定月的天数 
 * */  
public static int getMonthLastDay(int year, int month)  
{  
    Calendar a = Calendar.getInstance();  
    a.set(Calendar.YEAR, year);  
    a.set(Calendar.MONTH, month - 1);  
    a.set(Calendar.DATE, 1);//把日期设置为当月第一天  
    a.roll(Calendar.DATE, -1);//日期回滚一天,也就是最后一天  
    int maxDate = a.get(Calendar.DATE);  
    return maxDate;  
}

2.使用自己编写的函数实现

package test;  
  
import java.text.SimpleDateFormat;  
import java.util.Calendar;  
import java.util.Date;  
  
/** 
 * 日期工具类 by hpf  
 * */  
public class DateUtils  
{  
    //返回当前年月日  
    String getNowDate()  
    {  
        Date date = new Date();  
        String nowDate = new SimpleDateFormat("yyyy年MM月dd日").format(date);  
        return nowDate;  
    }  
  
    //返回当前年份  
    int getYear()  
    {  
        Date date = new Date();  
        String year = new SimpleDateFormat("yyyy").format(date);  
        return Integer.parseInt(year);  
    }  
  
    //返回当前月份  
    int getMonth()  
    {  
        Date date = new Date();  
        String month = new SimpleDateFormat("MM").format(date);  
        return Integer.parseInt(month);  
    }  
  
    //判断闰年  
    boolean isLeap(int year)  
    {  
        if (((year % 100 == 0) && year % 400 == 0) || ((year % 100 != 0) && year % 4 == 0))  
            return true;  
        else  
            return false;  
    }  
  
    //返回当月天数  
    int getDays(int year, int month)  
    {  
        int days;  
        int FebDay = 28;  
        if (isLeap(year))  
            FebDay = 29;  
        switch (month)  
        {  
            case 1:  
            case 3:  
            case 5:  
            case 7:  
            case 8:  
            case 10:  
            case 12:  
                days = 31;  
                break;  
            case 4:  
            case 6:  
            case 9:  
            case 11:  
                days = 30;  
                break;  
            case 2:  
                days = FebDay;  
                break;  
            default:  
                days = 0;  
                break;  
        }  
        return days;  
    }  
  
    //返回当月星期天数  
    int getSundays(int year, int month)  
    {  
        int sundays = 0;  
        SimpleDateFormat sdf = new SimpleDateFormat("EEEE");  
        Calendar setDate = Calendar.getInstance();  
        //从第一天开始  
        int day;  
        for (day = 1; day <= getDays(year, month); day++)  
        {  
            setDate.set(Calendar.DATE, day);  
            String str = sdf.format(setDate.getTime());  
            if (str.equals("星期日"))  
            {  
                sundays++;  
            }  
        }  
        return sundays;  
    }  
  
    public static void main(String[] args)  
    {  
        DateUtils du = new DateUtils();  
        System.out.println("今天日期是:" + du.getNowDate());  
        System.out.println("本月有" + du.getDays(du.getYear(), du.getMonth()) + "天");  
        System.out.println("本月有" + du.getSundays(du.getYear(), du.getMonth()) + "个星期天");  
    }  
}

 

2011-05-04 12:16:16 yunshangbuhe1 阅读数 125
Android 获取当前日期 时间很方便 直接调用Calendar类即可

定义变量


private int mHour;

private int mMinute;

private int mYear;

private int mMonth;

private int mDay;


调用如下

final Calendar c = Calendar.getInstance();

mYear = c.get(Calendar.YEAR); //获取当前年份

mMonth = c.get(Calendar.MONTH);//获取当前月份

mDay = c.get(Calendar.DAY_OF_MONTH);//获取当前月份的日期号码

mHour = c.get(Calendar.HOUR_OF_DAY);//获取当前的小时数

mMinute = c.get(Calendar.MINUTE);//获取当前的分钟数


本文来自CSDN博客,转载请标明出处:http://blog.csdn.net/Zengyangtech/archive/2010/05/04/5554989.aspx
2018-09-24 11:06:01 quanyechacsdn 阅读数 3911


测试机为小米8

开发工具AndroidStudio,使用组件GridView

实现步骤以及原理

  1. 通过Calendar获取当前年月日
  2. 获取指定年月的天数
  3. 得到当月一号是星期几
  4. 获取日期对象的列表数据:当月天数加上当月1号星期几之前的空白数据(比如1号是星期3,那么日期列表数据之前添加三个数据)
  5. 设置GridView的适配器

具体实现

  1. 用Calendar对象获取日期
    Calendar calendar = Calendar.getInstance(); currYear = calendar.get(Calendar.YEAR); currMouth = calendar.get(Calendar.MONTH);
  2. 获取对应年月的天数
      private int getMonthLastDay(int year, int month) {
        Calendar a = Calendar.getInstance();
        a.set(Calendar.YEAR, year);
        a.set(Calendar.MONTH, month - 1);
        a.set(Calendar.DATE, 1);//把日期设置为当月第一天
        a.roll(Calendar.DATE, -1);//日期回滚一天,也就是最后一天
        return a.get(Calendar.DATE);
    }
    
  3. 一号是星期几
		Calendar calendar = Calendar.getInstance();
        int currYear = calendar.get(Calendar.YEAR);
        int currMouth = calendar.get(Calendar.MONTH) + 1;
        int currDay = calendar.get(Calendar.DAY_OF_MONTH);
        calendar.set(year, mouth - 1, 0);

        int i1 = calendar.get(Calendar.DAY_OF_WEEK);//这就是星期几
  1. 得到日期数据列表
 public void requestData() {
        last_state = 0;
        state_count = 0;
        ArrayList<DateInfo> datas = new ArrayList<>();
        Calendar calendar = Calendar.getInstance();
        int currYear = calendar.get(Calendar.YEAR);
        int currMouth = calendar.get(Calendar.MONTH) + 1;
        int currDay = calendar.get(Calendar.DAY_OF_MONTH);
        calendar.set(year, mouth - 1, 0);

        int i1 = calendar.get(Calendar.DAY_OF_WEEK);
        if (i1 > 6)//如果大于6天,也就是一个星期的天数,就不用添加,否则显示一行空白
            i1 = 0;

        for (int i = 0; i < i1; i++) {
            datas.add(new DateInfo(true));
        }

        for (int i = 0; i < getMonthLastDay(year, mouth); i++) {
            DateInfo data = new DateInfo(year, mouth, i + 1);
            if (currYear == year && currMouth == mouth && currDay == i + 1)
                data.setToday(true);
            data.setState(new Random().nextInt(4));//设置这一天的状态的
            if (last_state == 0) {
                last_state = data.getState();
                state_count = 1;
            } else if (last_state == data.getState()) {
                ++state_count;
                datas.get(i + i1 - 1).setState_count(state_count);
                data.setState_count(state_count);
            } else {
                last_state = data.getState();
                state_count = 1;
            }
            datas.add(data);
        }
  }
  1. 最后继承自BaseAdapter,设置GridView的适配器
2018-05-08 15:42:15 weixin_38148680 阅读数 378

通过系统提供AIDL接口给,第三方应用调用,获取流量使用情况。

获取当月流量使用情况:

/**
 * Created by ybf
 */
 public List inivData() {
        INetworkStatsService mStatsService = null;
        INetworkStatsSession mStatsSession = null;
        NetworkTemplate mTemplate = null;
        NetworkStats sta = null;
        List<AppInfoBean>  lists = new ArrayList<>();
        try {
            long start = getStarttime();
            long end =System.currentTimeMillis();
            Log.e(TAG, "[start]=" + start + "[end]=" + end);
            mStatsService = INetworkStatsService.Stub.asInterface(ServiceManager.getService("netstats"));
            Log.e(TAG, "[mStatsService]="+mStatsService);
            mStatsSession = mStatsService.openSession();
            Log.e(TAG, "[mStatsSession]="+mStatsSession);
            mTemplate = buildTemplateMobileAll(getActiveSubscriberId(mContext));
            Log.e(TAG, "[getActiveSubscriberId(mContext)]="+getActiveSubscriberId(mContext));
            Log.e(TAG, "[mTemplate]="+mTemplate);
            sta = mStatsSession.getSummaryForAllUid(mTemplate, start, end, true);
            NetworkStats.Entry entry = null;
            int size = sta != null ? sta.size() : 0;
            Log.e(TAG, "[service-size-]" + size);
            for (int i = 0; i < size; i++) {
                entry = sta.getValues(i, entry);
                final int uid = entry.uid;
                long totalapp = entry.rxBytes + entry.txBytes;
                String sumtotal = Formatter.formatFileSize(mContext, totalapp);
                String name = null;
                switch (uid) {
                    case android.os.Process.SYSTEM_UID:
                        name = res.getString(R.string.process_kernel_label);
                        break;
                    case -4:
                        name = res.getString(R.string.data_usage_uninstalled_apps);
                        break;
                    case -5:
                        name = res.getString(R.string.tether_settings_title_all);
                        break;
                    default:
                       if(uid< 9999){
                            name = "null";
                        }else {
                            try {
                                name = getProgramNameByPackageName(mContext, uid);
                            } catch (Exception e) {
                                Log.e(TAG, "package name is null");
                            }
                        }
                        break;
                }
                AppInfoBean appInfo = new AppInfoBean();
                appInfo.setName(name);
                appInfo.setTotal(sumtotal);
                appInfo.setUid(uid);
                lists.add(appInfo);
                Log.e(TAG, "[uid]=" + uid + "[name]=" + name + "[total]=" + sumtotal);
            }
        } catch (Exception e) {
            // TODO: handle exception
            e.printStackTrace();
            e.toString();
        }
        return  lists;
    }

获取历史流量使用情况:

/**
 * Created by ybf
 */
 public List inivDataHistory(long start ,long end) {
        INetworkStatsService mStatsService = null;
        INetworkStatsSession mStatsSession = null;
        NetworkTemplate mTemplate = null;
        NetworkStats sta = null;
        List<AppInfoBean>  lists = new ArrayList<>();
        try {
            if(start == 0){
                start = getStarttime();
            }
           if(end == 0){
               end =System.currentTimeMillis();
           }
            Log.e(TAG, "[start]=" + start + "[end]=" + end);
            mStatsService = INetworkStatsService.Stub.asInterface(ServiceManager.getService("netstats"));
            Log.e(TAG, "[mStatsService]="+mStatsService);
            mStatsSession = mStatsService.openSession();
            Log.e(TAG, "[mStatsSession]="+mStatsSession);
            mTemplate = buildTemplateMobileAll(getActiveSubscriberId(mContext));
            Log.e(TAG, "[getActiveSubscriberId(mContext)]="+getActiveSubscriberId(mContext));
            Log.e(TAG, "[mTemplate]="+mTemplate);
            sta = mStatsSession.getSummaryForAllUid(mTemplate, start, end, true);
            NetworkStats.Entry entry = null;
            int size = sta != null ? sta.size() : 0;
            Log.e(TAG, "[service-size-]" + size);
            for (int i = 0; i < size; i++) {
                entry = sta.getValues(i, entry);
                final int uid = entry.uid;
                long totalapp = entry.rxBytes + entry.txBytes;
                String sumtotal = Formatter.formatFileSize(mContext, totalapp);
                String name = null;
                switch (uid) {
                    case android.os.Process.SYSTEM_UID:
                        name = res.getString(R.string.process_kernel_label);
                        break;
                    case -4:
                        name = res.getString(R.string.data_usage_uninstalled_apps);
                        break;
                    case -5:
                        name = res.getString(R.string.tether_settings_title_all);
                        break;
                    default:
                        if(uid< 9999){
                            name = "null";
                        }else {
                            try {
                                name = getProgramNameByPackageName(mContext, uid);
                            } catch (Exception e) {
                                Log.e(TAG, "package name is null");
                            }
                        }
                        break;
                }
                AppInfoBean appInfo = new AppInfoBean();
                appInfo.setName(name);
                appInfo.setTotal(sumtotal);
                appInfo.setUid(uid);
                lists.add(appInfo);
                Log.e(TAG, "[uid]=" + uid + "[name]=" + name + "[total]=" + sumtotal);
            }
        } catch (Exception e) {
            // TODO: handle exception
        }
        return  lists;
    }
2019-09-25 17:43:42 qq_34203714 阅读数 72

问题:

日期选择需求,展示年月和当月所有日期的同时,能够动态切换日期,同时今天要特别显示

分析:

页面元素主要包括,年  月  一个月的天和天对应的星期名

用户操作交互时,

首次进入需要获取当前日期的 年 月 和本月的全部天和星期

点击年月的上下箭头,需要月加减,遇到1月减或者12月加时,需要年份进行增减,同时 月份变化,也需要获取变化后的月天数和对应的星期名 并刷新

特殊需求:注意匹配今天,周显示为今天,同时本日的字变色,加圆背景

解决:

获取今天的日期信息

获取今日的日期信息
Calendar calendar = Calendar.getInstance();

获取上月字符串

//传入保存的Calendar calendar对象
public void getLastMouth(Calendar calendar){
    DateFormat df = new SimpleDateFormat("YYYY/MM");
    calendar.add(Calendar.MONTH, -1);
    date = (Date) calendar.getTime();
    String format = df.format(date);
    System.out.println(format); 
} 

获取下月字符串

//传入保存的Calendar calendar对象
public void getNextMouth(Calendar calendar){
    DateFormat df = new SimpleDateFormat("YYYY/MM");
    calendar.add(Calendar.MONTH, 1);
    date = (Date) calendar.getTime();
    String format = df.format(date);
    System.out.println(format); 
} 

获取对应月天数

    /**
     * 根据年 月 获取对应的月份 天数
        用保存的calendar获取
        calendar.get(Calendar.YEAR);
        calendar.get(Calendar.MOUTH);
     */
    public static int getDaysByYearMonth(int year, int month) {
        Calendar a = Calendar.getInstance();
        a.set(Calendar.YEAR, year);
        a.set(Calendar.MONTH, month - 1);
        a.set(Calendar.DATE, 1);
        a.roll(Calendar.DATE, -1);
        int maxDate = a.get(Calendar.DATE);
        return maxDate;
    } 

获取当天的周数

/**
     * 获取当天的周数
     *
     * @param date
     * @return
     */
    public static String getDaysOfWeek(Date date) {
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        int i = calendar.get(Calendar.DAY_OF_WEEK);
        switch (i) {
            case 1:
                return "周天" ;
            case 2:
                return “周一”;
            case 3:
                return “周二”;
            case 4:
                return “周三”;
            case 5:
                return “周四”;
            case 6:
                return “周五”;
            case 7:
                return “周六”;
            default:
                return "";
        }
    }

获取对应天数和周数的逻辑

Canlendar calendar = Canlendar.getInstance();
int monthDays=getDaysByYearMonth(calendar.get(Calendar.YEAR),calendar.get(Calendar.MOUTH));
for (int i = 0; i < monthDays; i++) {
     instance.set(year,month,i+1);
     dateInfoList.add( new DateInfoBean(instance.get(Calendar.YEAR),
                                               instance.get(Calendar.MONTH),
                                               instance.get(Calendar.DAY_OF_MONTH),
              
     DateUtil.getDaysOfWeek(instance.get(Calendar.DAY_OF_WEEK))));
}

这样就能获得当月所有的日期和对应日期的周名称

效果总结:

经过一番分析总结,发现功能并不复杂,主要在于日期的不断交换,ui上很简单,图标按钮和列表组合一下,及时刷新日期数据即可,相信大家也能很快掌握。

 

没有更多推荐了,返回首页