zoukankan      html  css  js  c++  java
  • 代码空间项目 -- 获取当前时间之前的某一天-Calender类的使用

    Calendar类的静态方法getInstance()可以初始化一个日历对象:Calendar now = Calendar.getInstance(); 
    1.Calendar的基本用法
    calendar.add(Calendar.DATE, -1);    //得到前一天
    calendar.add(Calendar.MONTH, -1);    //得到前一个月
    int year = calendar.get(Calendar.YEAR);
    int month = calendar.get(Calendar.MONTH)+1;
    2.Calendar和Date的转化
    (1) Calendar转化为Date
    Calendar cal=Calendar.getInstance();
    Date date=cal.getTime();
    (2) Date转化为Calendar
    Date date=new Date();
    Calendar cal=Calendar.getInstance();
    cal.setTime(date);
    3.格式化输出日期时间
    Date date=new Date();
    SimpleDateFormat df=new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
    4.案例
    a.网上找的小案例 判断当前日期是星期几
    public static int dayForWeek(String pTime) throws Exception {  
    SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");  
    Calendar c = Calendar.getInstance();  
    c.setTime(format.parse(pTime));  
    int dayForWeek = 0;  
    if(c.get(Calendar.DAY_OF_WEEK) == 1){  
      dayForWeek = 7;  
    }else{  
      dayForWeek = c.get(Calendar.DAY_OF_WEEK) - 1;  
    }  
    return dayForWeek;  

    b.项目中的案例 获取某一天的时间
    public String getTime(String condition){
            Date dNow = new Date();//当前时间
            Date dBefore = new Date();

            Calendar calendar = Calendar.getInstance();//得到日历
            calendar.setTime(dNow);//date转Calendar
            if(condition.equals("week")){
                calendar.add(Calendar.DAY_OF_MONTH, -7);//设置为前七天
            }else if(condition.equals("month")){
                calendar.add(Calendar.MONTH, -1);//设置为一个月前
            }
            dBefore = calendar.getTime();//Calendar转date

            SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd");//设置时间格式
            return sdf.format(dBefore);//返回日期
    }
  • 相关阅读:
    【POJ3613 Cow Relays】(广义矩阵乘法)
    【洛谷 P2483】 【模板】k短路([SDOI2010]魔法猪学院)(A*)
    【UVA1505】 Flood-it!(IDA*)
    【CF1095F】 Make It Connected(最小生成树)
    【SP1716】GSS3
    【洛谷 P1641】 [SCOI2010]生成字符串(Catalan数)
    【BZOJ 2351】Matrix(Hash)
    【CH1809】匹配统计(KMP)
    【洛谷 P2633】 Count on a tree(主席树,树上差分)
    【洛谷 P5341】 [TJOI2019]甲苯先生和大中锋的字符串(后缀自动机)
  • 原文地址:https://www.cnblogs.com/zmc-change/p/5374622.html
Copyright © 2011-2022 走看看