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

10,979 Responses

  1. The Venture Capital Trust Scheme is a tax advantaged scheme designed for a HMRC-Approved VCT company to chip in for shares in, lends money to small unquoted companies.

  2. These prices do not reflect trading costs, which can prevent arbitrage and thus the elimination predictability.

  3. There are many ways to start business and generate profits.

  4. I just like the valuable info you provide in your articles. I?ll bookmark your weblog and check once more right here frequently. I am somewhat certain I?ll be told lots of new stuff proper here! Best of luck for the next!

  5. The problem is that the Internal Revenue Service (IRS) doesn’t allow you to deduct expenses related to hobbies.

  6. Backlinks are certainly one of the key components in Seo, and are hyperlinks from
    different websites to your web site. Actually, there are
    numerous ranking components. However, on-web page factors only form a
    part of the search optimisation picture.

    My web page power of backlinks

  7. Jamesric表示:

    cytotec abortion pill: buy cytotec online – buy cytotec over the counter

  8. They are analogous to mutual funds wherein a fund is similarly set up expressly for trading in equity, except that mutual funds are open to public subscription whereas commodity pools and hedge funds are private.

  9. Good web site! I really love how it is easy on my eyes and the data are well written. I am wondering how I might be notified when a new post has been made. I have subscribed to your feed which must do the trick! Have a nice day!

  10. Jamesric表示:

    lasix 100 mg tablet: furosemide online – lasix online

  11. Moreover, we can make your dream come true by helping you out to have your dream home in an amazing contemporary trident structure, the Icon on Bricell, which is designed by Yoo inspired by Starck.

  12. Jamesric表示:

    lisinopril 10 mg canada cost: Lisinopril refill online – lisinopril 20 25 mg tab

  13. Private equity clients and investors can execute potential deals while keeping track of their portfolio through deal and post-deal solutions.

  14. One other thing I would like to say is that as opposed to trying to fit all your online degree classes on days of the week that you end work (since most people are tired when they get home), try to get most of your sessions on the saturdays and sundays and only a couple of courses on weekdays, even if it means a little time away from your weekend break. This pays off because on the week-ends, you will be far more rested and also concentrated on school work. Thx for the different guidelines I have learned from your website.

  15. Hello there, I found your site via Google while searching for a related topic, your web site came up, it looks good. I have bookmarked it in my google bookmarks.

  16. Xzginv表示:

    gabapentin 600mg without prescription – order neurontin 800mg without prescription sulfasalazine 500mg over the counter

  17. Occasionally, you will acquire a demo statement telling you, what commodities you have in your demo account.

  18. Why, turkey dinner, of course!

  19. hobbs shaw表示:

    Hello, i read your blog from time to time and i own a similar one and i was just wondering if you get a lot of spam feedback? If so how do you stop it, any plugin or anything you can advise? I get so much lately it’s driving me crazy so any support is very much appreciated.

  20. Hi my friend! I wish to say that this article is amazing, nice written and include approximately all significant infos. I?d like to see more posts like this.

  21. Hey! I could have sworn I’ve been to this website before but after browsing through some of the post I realized it’s new to me. Anyhow, I’m definitely glad I found it and I’ll be book-marking and checking back frequently!

  22. Thanks for your article. What I want to point out is that while searching for a good internet electronics retail outlet, look for a web-site with full information on critical factors such as the personal privacy statement, protection details, any payment guidelines, and various terms as well as policies. Constantly take time to look at help and also FAQ areas to get a greater idea of what sort of shop functions, what they are able to do for you, and just how you can use the features.

  23. Sazrpqf表示:

    Здравствуйте!
    Диплом бакалавра
    telegra.ph/gde-v-moskve-mozhno-kupit-diplom-08-22-2

  24. Sazrvbl表示:

    Здравствуйте!
    Диплом любой специальности
    telegra.ph/kupit-diplom-moryaka-08-22

  25. Trefjcn表示:

    Привет!
    Стоимость дипломов высшего и среднего образования и процесс их получения
    whitepower.clanweb.eu/profile.php?lookup=25765
    Окажем помощь!.

  26. Hello there, I found your website via Google while looking for a related topic, your web site came up, it looks good. I have bookmarked it in my google bookmarks.

  27. He said that it would be too early to tell whether the economy was growing during the first quarter of 2012.

  28. I’m not sure exactly why but this blog 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 and see if the problem still exists.

  29. Say the stock trades at $63 one enterprise day prior to the ex-date.

  30. Dino Game 127表示:

    Today, I went to the beach with my kids. I found a sea shell and gave it to my 4 year old daughter and said “You can hear the ocean if you put this to your ear.” She put the shell to her ear and screamed. There was a hermit crab inside and it pinched her ear. She never wants to go back! LoL I know this is entirely off topic but I had to tell someone!

發佈留言

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