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,342 Responses

  1. Thanks for your intriguing article. One other problem is that mesothelioma is generally attributable to the breathing of fibers from asbestos, which is a carcinogenic material. Its commonly witnessed among staff in the engineering industry who definitely have long experience of asbestos. It’s also caused by moving into asbestos insulated buildings for some time of time, Genetic makeup plays a huge role, and some persons are more vulnerable towards the risk as compared to others.

  2. bet88dog表示:

    One thing I have actually noticed is that often there are plenty of fallacies regarding the banking institutions intentions while talking about property foreclosure. One fantasy in particular would be the fact the bank needs to have your house. The lending company wants your dollars, not your property. They want the cash they loaned you together with interest. Keeping away from the bank is only going to draw a foreclosed conclusion. Thanks for your article.

  3. Richardaudit表示:

    https://predpharmnet.shop/# over the counter prednisone pills

  4. BrianTom表示:

    prednisone without prescription medication Pred Pharm Net prednisone pill

  5. Профессиональный сервисный центр по ремонту бытовой техники с выездом на дом.
    Мы предлагаем:ремонт крупногабаритной техники в москве
    Наши мастера оперативно устранят неисправности вашего устройства в сервисе или с выездом на дом!

  6. alarme Ajax表示:

    Thanks for expressing your ideas. One thing is that college students have a selection between government student loan plus a private student loan where its easier to opt for student loan debt consolidation than over the federal student loan.

  7. Michaelscoob表示:

    Clom Fast Pharm: can you get generic clomid pills – Clom Fast Pharm

  8. Michaelscoob表示:

    generic for amoxicillin: AmOnlinePharm – amoxicillin 500mg capsules

  9. Wow, superb blog layout! How long have you been blogging for? you made blogging look easy. The overall look of your website is magnificent, as well as the content!

  10. Major thankies for the blog. Want more.

  11. LanceFen表示:

    buy amoxicillin 500mg capsules uk: amoxicillin 500mg price in canada – AmOnlinePharm

  12. These days of austerity along with relative anxiety about getting debt, lots of people balk contrary to the idea of employing a credit card to make purchase of merchandise or even pay for a trip, preferring, instead to rely on a tried along with trusted way of making repayment – raw cash. However, if you’ve got the cash available to make the purchase fully, then, paradoxically, that’s the best time for you to use the cards for several reasons.

  13. Danieldrymn表示:

    lisinopril 20 25 mg tab: Lisin Express – how much is lisinopril 40 mg

  14. Uncertain whether a secured loan is right for you? Understand the benefits, such as more favourable terms and larger borrowing amounts.

  15. LanceFen表示:

    AmOnlinePharm: AmOnlinePharm – amoxicillin 250 mg

  16. bet88dog表示:

    One important thing is that while you are searching for a student loan you may find that you’ll need a cosigner. There are many circumstances where this is true because you could find that you do not employ a past credit history so the loan provider will require that you have someone cosign the loan for you. Interesting post.

  17. bet88dog表示:

    I do accept as true with all the concepts you’ve introduced to your post. They’re very convincing and will certainly work. Nonetheless, the posts are too brief for novices. May you please prolong them a bit from subsequent time? Thank you for the post.

  18. Richardaudit表示:

    https://amonlinepharm.com/# AmOnlinePharm

  19. Grace Evans表示:

    Thinking about a loan against your home to manage your debts? Find out more and check what solutions may be available to you.

  20. BrianTom表示:

    Clom Fast Pharm Clom Fast Pharm can you buy clomid for sale

  21. It’s a shame you don’t have a donate button! I’d most certainly donate to this superb blog! I suppose for now i’ll settle for book-marking and adding your RSS feed to my Google account. I look forward to brand new updates and will share this blog with my Facebook group. Chat soon!

  22. Michaelscoob表示:

    Clom Fast Pharm: Clom Fast Pharm – where can i get cheap clomid for sale

  23. great points altogether, you simply gained a new reader. What would you recommend about your post that you made a few days in the past? Any sure?

  24. bet88dog表示:

    Attractive element of content. I simply stumbled upon your site and in accession capital to claim that I acquire in fact enjoyed account your blog posts. Anyway I will be subscribing to your feeds or even I success you access constantly rapidly.

  25. I’m not sure exactly why but this web site is loading incredibly slow for me. Is anyone else having this problem or is it a problem on my end? I’ll check back later on and see if the problem still exists.

  26. qq88表示:

    I have noticed that over the course of constructing a relationship with real estate owners, you’ll be able to get them to understand that, in each and every real estate financial transaction, a payment is paid. Ultimately, FSBO sellers really don’t “save” the commission payment. Rather, they try to win the commission by doing an agent’s work. In doing so, they spend their money plus time to conduct, as best they might, the obligations of an realtor. Those responsibilities include getting known the home through marketing, showing the home to willing buyers, building a sense of buyer emergency in order to make prompt an offer, scheduling home inspections, handling qualification assessments with the loan provider, supervising maintenance, and facilitating the closing.

  27. Richardaudit表示:

    https://predpharmnet.shop/# buy prednisone online canada

  28. One other issue issue is that video games can be serious as the name indicated with the most important focus on finding out rather than amusement. Although, it comes with an entertainment part to keep your young ones engaged, every single game will likely be designed to focus on a specific expertise or programs, such as mathematics or scientific research. Thanks for your article.

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

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