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...

36,444 Responses

  1. Josephsip表示:

    alo789: alo 789 – dang nh?p alo789

  2. Hello just wanted to give you a quick heads up and let you know a few of the pictures aren’t loading correctly. I’m not sure why but I think its a linking issue. I’ve tried it in two different browsers and both show the same results.

  3. I appreciate you sharing this post.Really looking forward to read more. Want more.Loading…

  4. Rubengax表示:

    alo789in dang nh?p alo789 alo 789

  5. JasonBib表示:

    Discover Bangladesh’s most trusted online gaming destinations through BDCasinoRatings.online – your premier guide to licensed platforms offering seamless Bkash/Nagad transactions and localized Bangla support. Our expert-curated rankings highlight casinos with fast Taka payouts, exciting Cricket betting options, and generous welcome bonuses tailored for Bangladeshi players. Stay informed with real-time updates on safety standards and exclusive promotions across South Asia’s fastest-growing iGaming market. https://bdcasinoratings.online/

  6. Josephsip表示:

    k8: link vao k8 – k8 bet

  7. Rubengax表示:

    789alo alo789 789alo

  8. RodolfoKap表示:

    https://www.tapatalk.com/groups/dzerjinsky/viewtopic.php?f=2&t=43794&from_new_topic=1 – промокод мелбет на бесплатную ставку

  9. Josephsip表示:

    nha cai 88bet: nha cai 88bet – keo nha cai 88bet

  10. Josephsip表示:

    k8vip: k8 th? dam – k8vip

  11. Curtismence表示:

    https://k8viet.guru/# nha cai k8

  12. Curtismence表示:

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

  13. Stevenkated表示:

    https://k8viet.guru/# nha cai k8

  14. Hi, Neat post. There’s a problem with your web site in internet explorer, would check this? IE still is the market leader and a large portion of people will miss your fantastic writing because of this problem.

  15. Rubengax表示:

    nha cai 88bet 88bet slot 88 bet

  16. Hey there are using WordPress for your site platform? I’m new to the blog world but I’m trying to get started and set up my own. Do you require any coding expertise to make your own blog? Any help would be greatly appreciated!

  17. Stevenkated表示:

    https://alo789.auction/# alo789 chinh th?c

  18. Also I believe that mesothelioma is a unusual form of cancers that is usually found in these previously subjected to asbestos. Cancerous tissue form in the mesothelium, which is a protective lining that covers many of the body’s bodily organs. These cells generally form in the lining with the lungs, abdominal area, or the sac which actually encircles the heart. Thanks for discussing your ideas.

  19. Thanks for the tips on credit repair on your blog. Things i would tell people is to give up the actual mentality that they may buy at this point and shell out later. Being a society we tend to repeat this for many issues. This includes getaways, furniture, and items we would like. However, you must separate your current wants out of the needs. As long as you’re working to fix your credit score you have to make some trade-offs. For example it is possible to shop online to economize or you can turn to second hand merchants instead of pricey department stores for clothing.

  20. Hi, i think that i saw you visited my website thus i came to ?return the favor?.I am trying to find things to enhance my web site!I suppose its ok to use a few of your ideas!!

  21. I learned more new stuff on this weight loss issue. One particular issue is a good nutrition is vital if dieting. A tremendous reduction in fast foods, sugary meals, fried foods, sweet foods, beef, and white flour products may perhaps be necessary. Keeping wastes parasitic organisms, and poisons may prevent goals for losing weight. While a number of drugs for the short term solve the condition, the terrible side effects usually are not worth it, plus they never supply more than a short lived solution. It is just a known undeniable fact that 95 of diet plans fail. Thanks for sharing your notions on this weblog.

  22. Do you mind if I quote a couple of your posts as long as I provide credit and sources back to your weblog? My blog site is in the very same area of interest as yours and my visitors would definitely benefit from a lot of the information you provide here. Please let me know if this alright with you. Regards!

  23. Stevenkated表示:

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

  24. Admiring the time and energy you put into your website and in depth information you provide. It’s good to come across a blog every once in a while that isn’t the same outdated rehashed information. Fantastic read! I’ve saved your site and I’m adding your RSS feeds to my Google account.

  25. A lot of of the things you claim happens to be supprisingly accurate and that makes me wonder why I had not looked at this in this light before. Your piece truly did turn the light on for me as far as this specific topic goes. Nevertheless at this time there is one particular factor I am not necessarily too cozy with and whilst I try to reconcile that with the actual core theme of the point, allow me see exactly what all the rest of the readers have to say.Very well done.

  26. Josephsip表示:

    88 bet: 88bet slot – 88bet slot

  27. esta usa表示:

    Nice post. I was checking continuously this blog and I’m impressed! Extremely useful information specially the last part 🙂 I care for such info much. I was seeking this certain information for a long time. Thank you and good luck.

  28. esta usa表示:

    Usually I do not learn post on blogs, but I would like to say that this write-up very forced me to check out and do so! Your writing taste has been surprised me. Thanks, very great article.

發佈留言

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