Java 各種時間上的操作範例

分享一些在專案中用到JAVA與日期相關的操作,包括:

  • 取得目前的年、月、日
  • 判斷兩個日期的大小
  • 計算兩個日期的差距
  • 取得昨天的日期
  • 取得上個月的開始與結束日
package CDIT.stanley;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;
import java.util.Calendar;

public class dateOperation {
	
	public static int differentDays(Date date1,Date date2){
        Calendar cal1 = Calendar.getInstance();
        cal1.setTime(date1);
        
        Calendar cal2 = Calendar.getInstance();
        cal2.setTime(date2);
        int day1= cal1.get(Calendar.DAY_OF_YEAR);
        int day2 = cal2.get(Calendar.DAY_OF_YEAR);
        
        int year1 = cal1.get(Calendar.YEAR);
        int year2 = cal2.get(Calendar.YEAR);
        if(year1 != year2){
            int timeDistance = 0 ;
            for(int i = year1 ; i < year2 ; i ++){
                if(i%4==0 && i%100!=0 || i%400==0){
                    timeDistance += 366;
                }
                else{
                    timeDistance += 365;
                }
            }
            return timeDistance + (day2-day1) ;
        }
        else{
            return day2-day1;
        }
    }
	
	public static Date getFirstMonthDay(Calendar calendar) {
		calendar.set(Calendar.DATE, calendar.getActualMinimum(Calendar.DATE));
		return calendar.getTime();
	}

	public static Date getLastMonthDay(Calendar calendar) {
		calendar.set(Calendar.DATE, calendar.getActualMaximum(Calendar.DATE));
		return calendar.getTime();
	}
	
    public static void main(String[] args) throws ParseException {
    	
    	//取得目前的年、月、日
		Calendar calendar = Calendar.getInstance();	
		System.out.println("今天是" + calendar.get(Calendar.YEAR) + "年" + (calendar.get(Calendar.MONTH) + 1) + "月" + calendar.get(Calendar.DAY_OF_MONTH) + "日");
		System.out.println("==================================================");
    	//輸出:今天是2017年8月24日
		
		//判斷兩個日期的大小
    	SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd", Locale.TAIWAN);
    	Date date1 = sdf.parse("2017-08-23");
    	Date date2 = sdf.parse("2016-09-22");
		System.out.println("Date1 < Date2 : " + date1.before(date2));
		System.out.println("Date1 > Date2 : " + date1.after(date2));
		System.out.println("==================================================");
		//輸出:Date1 < Date2 : false、Date1 > Date2 : true
		
		//計算兩個日期的差距
		System.out.println("Date1 & Date2 差距 : " + differentDays(date1 , date2) + "天");
		System.out.println("==================================================");
		//輸出:Date1 & Date2 差距 : 31天
		
		//取得昨天的日期
		calendar = Calendar.getInstance();
		calendar.add(Calendar.DATE, -1);
		String  yestedayDate = sdf.format(calendar.getTime());
		System.out.println("昨天是" + yestedayDate);
		System.out.println("==================================================");
		//輸出:昨天是2017-08-23
		
		//取得上個月的開始與結束日
		calendar = Calendar.getInstance();
		calendar.add(Calendar.MONTH,-1);
		String monthDayFirst = sdf.format(getFirstMonthDay(calendar));
		String monthDayLast = sdf.format(getLastMonthDay(calendar));
		System.out.println("上個月的第一天是" + monthDayFirst);
		System.out.println("上個月的最後一天是" + monthDayLast);
		System.out.println("==================================================");
		//輸出:上個月的第一天是2017-07-01、上個月的最後一天是2017-07-31
    }
}

You may also like...

35,031 Responses

  1. Curtismence表示:

    https://88betviet.pro/# 88bet slot

  2. Josephsip表示:

    88 bet: nha cai 88bet – 88bet slot

  3. One thing I would really like to touch upon is that weightloss program fast can be carried out by the appropriate diet and exercise. Your size not only affects appearance, but also the general quality of life. Self-esteem, despression symptoms, health risks, in addition to physical abilities are damaged in weight gain. It is possible to just make everything right but still gain. If this happens, a problem may be the root cause. While a lot of food but not enough workout are usually responsible, common health concerns and widespread prescriptions might greatly help to increase size. Thanks for your post right here.

  4. Definitely imagine that which you stated. Your favourite justification seemed to be at the web the easiest thing to keep in mind of. I say to you, I certainly get irked while people consider issues that they plainly do not realize about. You controlled to hit the nail upon the highest and outlined out the entire thing without having side effect , other folks could take a signal. Will probably be back to get more. Thanks

  5. Many beach locations are residence to various wildlife, including seabirds, marine life, and coastal plants.

  6. Stevenkated表示:

    http://88betviet.pro/# nha cai 88bet

  7. Rubengax表示:

    alo789in alo789 dang nh?p alo789 chinh th?c

  8. You really make it seem so easy together with your presentation however I to find this topic to be really one thing that I believe I might never understand. It sort of feels too complex and extremely broad for me. I am having a look ahead for your next post, I?ll try to get the hang of it!

  9. Rubengax表示:

    alo789 chinh th?c alo789 dang nh?p alo 789

  10. The ESTA Control Protocols Plugfest organisers introduced that a dwell, informal round-desk dialogue will probably be made accessible to the general public via a free WebEx video convention.

  11. Thank you for another informative website. Where else could I get that type of information written in such an ideal way? I have a project that I am just now working on, and I have been on the look out for such information.

  12. Thank you for sharing superb informations. Your site is so cool. I’m impressed by the details that you have on this web site. It reveals how nicely you understand this subject. Bookmarked this web page, will come back for more articles. You, my pal, ROCK! I found simply the info I already searched everywhere and just could not come across. What an ideal web site.

  13. Curtismence表示:

    http://alo789.auction/# alo789 dang nh?p

  14. Stevenkated表示:

    https://88betviet.pro/# nha cai 88bet

  15. Rubengax表示:

    88bet slot keo nha cai 88bet 88bet slot

  16. Josephsip表示:

    nha cai k8: k8 – k8

  17. Baldino denied that was the reason, reminding the Commissioner that Martini’s father-in-law was also an architect.

  18. Stevenkated表示:

    http://88betviet.pro/# 88bet slot

  19. Josephsip表示:

    88bet: 88 bet – 188bet 88bet

  20. One thing I’d really like to say is always that car insurance cancelling is a hated experience and if you’re doing the correct things as a driver you may not get one. Many people do are sent the notice that they’ve been officially dumped by their own insurance company they then have to scramble to get extra insurance after a cancellation. Cheap auto insurance rates are usually hard to get after the cancellation. Knowing the main reasons pertaining to auto insurance cancelling can help motorists prevent completely losing in one of the most significant privileges obtainable. Thanks for the ideas shared by your blog.

  21. Hi! This is kind of off topic but I need some help from an established blog. Is it very hard to set up your own blog? I’m not very techincal but I can figure things out pretty quick. I’m thinking about making my own but I’m not sure where to begin. Do you have any ideas or suggestions? Thank you

  22. What cake flavors go well together?

  23. Admiring the dedication you put into your site and detailed information you offer. It’s great to come across a blog every once in a while that isn’t the same unwanted rehashed material. Excellent read! I’ve saved your site and I’m including your RSS feeds to my Google account.

  24. This article is a breath of fresh air! The author’s distinctive perspective and perceptive analysis have made this a truly engrossing read. I’m appreciative for the effort he has put into producing such an educational and mind-stimulating piece. Thank you, author, for providing your expertise and stimulating meaningful discussions through your brilliant writing!

  25. 1win_spsi表示:

    1 вин вход 1win812.ru .

發佈回覆給「Curtismence」的留言 取消回覆

發佈留言必須填寫的電子郵件地址不會公開。