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

  1. A true auto fan knows all of those gritty and fun details that go on behind the scenes and under the hood throughout a vehicle’s history.

  2. bad medical表示:

    I have been exploring for a bit for any high quality articles or weblog posts in this kind of space . Exploring in Yahoo I at last stumbled upon this web site. Reading this information So i am satisfied to exhibit that I’ve an incredibly good uncanny feeling I came upon just what I needed. I such a lot no doubt will make sure to do not put out of your mind this website and provides it a glance on a constant basis.

  3. What?s Taking place i am new to this, I stumbled upon this I have discovered It absolutely helpful and it has aided me out loads. I hope to give a contribution & assist other customers like its helped me. Good job.

  4. running man 4表示:

    A further issue is that video games can be serious anyway with the primary focus on studying rather than amusement. Although, it has an entertainment feature to keep children engaged, each one game is frequently designed to focus on a specific group of skills or area, such as mathematics or technology. Thanks for your article.

  5. Jamesric表示:

    order lisinopril from mexico: Lisinopril refill online – lisinopril 20mg

  6. medical bad表示:

    I have discovered some new items from your web page about computer systems. Another thing I’ve always presumed is that computer systems have become a specific thing that each household must have for some reasons. They offer convenient ways to organize households, pay bills, go shopping, study, tune in to music and in some cases watch shows. An innovative solution to complete many of these tasks is with a mobile computer. These pcs are mobile ones, small, effective and convenient.

  7. Jamesric表示:

    tamoxifen medication: is nolvadex legal – tamoxifen chemo

  8. It?s really a cool and useful piece of information. I am glad that you shared this useful information with us. Please keep us up to date like this. Thanks for sharing.

  9. Jamesric表示:

    aromatase inhibitors tamoxifen: buy tamoxifen citrate – arimidex vs tamoxifen bodybuilding

  10. Unquestionably imagine that which you stated. Your favorite justification seemed to be at the internet the simplest factor to understand of. I say to you, I definitely get irked while other people think about concerns that they plainly do not recognize about. You managed to hit the nail upon the highest and also outlined out the entire thing with no need side effect , people can take a signal. Will likely be again to get more. Thanks

  11. Greetings! I’ve been reading your blog for some time now and finally got the courage to go ahead and give you a shout out from Porter Tx! Just wanted to mention keep up the good work!

  12. Less stress and more flexibility were the reasons cited, which, you’ll remember from the introduction, are both leading reasons for seeking a change in the first place.

  13. An automatic and automatic forex trading basically utilizes a software method to ‘anticipate’ goes up and falls in up-to-dateness rates and additionally make profitable trading judgements.

  14. Those individual track settings are already locked in by the mixing engineer.

  15. Great write-up, I am regular visitor of one?s web site, maintain up the excellent operate, and It’s going to be a regular visitor for a lengthy time.

  16. I used to be recommended this web site via my cousin. I’m not certain whether or not this submit is written through him as no one else recognise such certain about my problem. You’re amazing! Thanks!

  17. I know this if off topic but I’m looking into starting my own blog and was wondering what all is needed to get setup? I’m assuming having a blog like yours would cost a pretty penny? I’m not very internet smart so I’m not 100 sure. Any tips or advice would be greatly appreciated. Kudos

  18. Greetings from Colorado! I’m bored to tears at work so I decided to check out your site on my iphone during lunch break. I love the knowledge you present here and can’t wait to take a look when I get home. I’m shocked at how quick your blog loaded on my cell phone .. I’m not even using WIFI, just 3G .. Anyways, amazing site!

  19. For proper control over your wealth, an avail professional wealth management services which can help you distribute your investments inside a broad and diverse portfolio.

  20. Match this dog to its breed.

  21. Australian Securities & Investments Commissionaccess.

  22. Hey, you used to write magnificent, but the last few posts have been kinda boring? I miss your super writings. Past several posts are just a little out of track! come on!

  23. This page was last edited on 23 March 2024, at 15:25 (UTC).

  24. DanielTet表示:

    cytotec pills buy online https://lisinopril.guru/# lisinopril 250 mg
    lasix for sale

  25. According to recent studies, nearly 6 in 10 people in the United States are affected by mental health conditions.

  26. When you think Transformers for girls, you probably don’t think about ladies that turn into cupcakes.

  27. たゆたう表示:

    These conflicts not only endanger the lives of both humans and tigers but also contribute to negative perceptions and attitudes towards the species.

  28. One thing I want to say is that before buying more laptop or computer memory, take a look at the machine in to which it will be installed. When the machine is running Windows XP, for instance, the particular memory ceiling is 3.25GB. Adding greater than this would merely constitute any waste. Be sure that one’s mother board can handle the particular upgrade amount, as well. Great blog post.

  29. That’s where forex coaches can help to rebuild confidence.

  30. Hello There. I found your blog using msn. This is a very well written article. I?ll be sure to bookmark it and come back to read more of your useful information. Thanks for the post. I?ll certainly return.

發佈留言

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