java獲取當月天數,指定年月的天數,指定日期獲取對應星期 .


 
         
 1 package huolongluo.family.util;
 2 
 3 import java.text.SimpleDateFormat;
 4 import java.util.Calendar;
 5 import java.util.Date;
 6 
 7 /**
 8  * Created by 火龍裸 on 2018/7/13.
 9  */
10 
11 public class Number_Of_Days
12 {
13     /**
14      * 獲取當月的 天數
15      */
16     public static int getCurrentMonthDay()
17     {
18         Calendar a = Calendar.getInstance();
19         a.set(Calendar.DATE, 1);
20         a.roll(Calendar.DATE, -1);
21         int maxDate = a.get(Calendar.DATE);
22         return maxDate;
23     }
24 
25     /**
26      * 根據 年、月 獲取對應的月份 的 天數
27      */
28     public static int getDaysByYearMonth(int year, int month)
29     {
30         Calendar a = Calendar.getInstance();
31         a.set(Calendar.YEAR, year);
32         a.set(Calendar.MONTH, month - 1);
33         a.set(Calendar.DATE, 1);
34         a.roll(Calendar.DATE, -1);
35         int maxDate = a.get(Calendar.DATE);
36         return maxDate;
37     }
38 
39     /**
40      * 根據日期 找到對應日期的 星期幾
41      *
42      * @param date 比如傳參:2018-07-13 將返回“周五”
43      */
44     public static String getDayOfWeekByDate(String date)
45     {
46         String dayOfweek = "-1";
47         try
48         {
49             SimpleDateFormat myFormatter = new SimpleDateFormat("yyyy-MM-dd");
50             Date myDate = myFormatter.parse(date);
51             SimpleDateFormat formatter = new SimpleDateFormat("E");
52             String str = formatter.format(myDate);
53             dayOfweek = str;
54         }
55         catch (Exception e)
56         {
57             System.out.println("錯誤!");
58         }
59         return dayOfweek;
60     }
61 }

 

這里添加另一個獲取具體星期幾的獲取方法:

/**
 * 根據當前日期獲得是星期幾
 * time=yyyy-MM-dd
 * @return
 */
public static String getWeek(String time) {
    String Week = "";
    SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
    Calendar c = Calendar.getInstance();
    try {
        c.setTime(format.parse(time));
    } catch (ParseException e) {
        e.printStackTrace();
    }

    int wek=c.get(Calendar.DAY_OF_WEEK);

    if (wek == 1) {
        Week += "星期日";
    }
    if (wek == 2) {
        Week += "星期一";
    }
    if (wek == 3) {
        Week += "星期二";
    }
    if (wek == 4) {
        Week += "星期三";
    }
    if (wek == 5) {
        Week += "星期四";
    }
    if (wek == 6) {
        Week += "星期五";
    }
    if (wek == 7) {
        Week += "星期六";
    }
    return Week;
}

 

 

補充一條,獲取系統當前時間:

final DateFormat df = DateFormat.getDateTimeInstance(DateFormat.MEDIUM, DateFormat.MEDIUM);
String comment = "Added on " + df.format(new Date());
Log.e("當前時間為" + comment);

打印出來的格式為:xxxx年xx月xx日 xx:xx:xx


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM