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

11,294 Responses

  1. Hello there, You’ve performed a fantastic job. I will definitely digg it and in my opinion recommend to my friends. I am sure they’ll be benefited from this web site.

  2. Leonardpar表示:

    http://edpillpharmacy.store/# online ed medicine

  3. Leonardpar表示:

    https://indiapharmacy.shop/# reputable indian pharmacies

  4. DouglasGed表示:

    reputable indian pharmacies: Indian pharmacy international shipping – indian pharmacy online

  5. DouglasGed表示:

    reputable indian online pharmacy: Indian pharmacy international shipping – best online pharmacy india

  6. Howdy! I’m at work surfing around your blog from my new iphone 4! Just wanted to say I love reading through your blog and look forward to all your posts! Carry on the superb work!

  7. the fabulous表示:

    I beloved as much as you will obtain performed right here. The caricature is attractive, your authored subject matter stylish. however, you command get got an edginess over that you would like be turning in the following. sick definitely come further beforehand again since exactly the same nearly a lot continuously inside case you shield this hike.

  8. DouglasGed表示:

    medicine in mexico pharmacies: mexico drug stores pharmacies – buying from online mexican pharmacy

  9. Hello! I just wanted to ask if you ever have any problems with hackers? My last blog (wordpress) was hacked and I ended up losing many months of hard work due to no backup. Do you have any solutions to protect against hackers?

  10. Please let me know if you’re looking for a article writer for your blog. You have some really good posts and I believe I would be a good asset. If you ever want to take some of the load off, I’d love to write some articles for your blog in exchange for a link back to mine. Please send me an e-mail if interested. Cheers!

  11. great put up, very informative. I wonder why the opposite specialists of this sector do not realize this. You should proceed your writing. I am sure, you’ve a huge readers’ base already!

  12. Thanks for the concepts you have shared here. Also, I believe there are some factors which will keep your insurance premium lower. One is, to take into consideration buying vehicles that are within the good directory of car insurance companies. Cars which might be expensive are more at risk of being stolen. Aside from that insurance coverage is also based on the value of the car, so the more costly it is, then the higher this premium you pay.

  13. Leonardpar表示:

    http://edpillpharmacy.store/# buy erectile dysfunction pills

  14. Right now it appears like WordPress is the best blogging platform out there right now. (from what I’ve read) Is that what you are using on your blog?

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

  16. Yrefdsx表示:

    Здравствуйте!
    Приобрести диплом любого университета.
    krdlogoped.blogspot.com/2018/02/blog-post_95

  17. I have realized that over the course of making a relationship with real estate entrepreneurs, you’ll be able to get them to understand that, in each and every real estate purchase, a commission is paid. Finally, FSBO sellers don’t “save” the commission payment. Rather, they struggle to win the commission through doing an agent’s task. In doing this, they expend their money plus time to accomplish, as best they are able to, the obligations of an broker. Those tasks include displaying the home by means of marketing, introducing the home to prospective buyers, building a sense of buyer emergency in order to make prompt an offer, preparing home inspections, taking on qualification checks with the loan company, supervising fixes, and aiding the closing of the deal.

  18. empress ki表示:

    In the grand pattern of things you actually get an A+ just for effort and hard work. Where exactly you actually confused everybody ended up being on your facts. As they say, the devil is in the details… And that could not be much more accurate in this article. Having said that, let me inform you just what exactly did give good results. The authoring is actually extremely persuasive which is possibly why I am taking the effort to opine. I do not really make it a regular habit of doing that. Second, even though I can certainly notice the jumps in logic you come up with, I am definitely not confident of exactly how you appear to unite your points that make your conclusion. For right now I shall yield to your position however wish in the future you link the facts much better.

  19. Trefiey表示:

    Здравствуйте!
    Сколько стоит диплом высшего и среднего образования и как это происходит?
    ifreemax.ru/2015/06/forum-madrid-startup-weekend-2015
    Рады помочь!.

  20. Thanks for the suggestions you have contributed here. One more thing I would like to convey is that laptop memory demands generally go up along with other advancements in the technological innovation. For instance, as soon as new generations of processor chips are brought to the market, there is certainly usually a matching increase in the shape demands of both the laptop memory as well as hard drive space. This is because the application operated by means of these processors will inevitably surge in power to leverage the new technological know-how.

  21. very nice submit, i certainly love this web site, carry on it

  22. Youre so cool! I dont suppose Ive learn something like this before. So good to seek out any person with some unique ideas on this subject. realy thank you for beginning this up. this web site is one thing that’s needed on the internet, somebody with a bit of originality. helpful job for bringing one thing new to the internet!

  23. DouglasGed表示:

    best india pharmacy: Online pharmacy USA – indian pharmacy

  24. These intermediaries include pension funds, banks, and insurance companies.

  25. DouglasGed表示:

    buying prescription drugs in mexico: Medicines Mexico – purple pharmacy mexico price list

  26. Lazrrkq表示:

    Привет!
    Мы изготавливаем дипломы психологов, юристов, экономистов и любых других профессий по выгодным ценам.
    telegra.ph/lgoty-detyam-iz-mnogodetnyh-semej-pri-postuplenii-v-vuz-ukraina-08-02

  27. Many thanks for this article. I would also like to say that it can be hard while you are in school and just starting out to initiate a long credit standing. There are many students who are simply trying to make it through and have a long or good credit history can occasionally be a difficult thing to have.

  28. What i don’t understood is actually how you’re not really much more well-liked than you may be right now. You are so intelligent. You realize therefore considerably relating to this subject, made me personally consider it from a lot of varied angles. Its like women and men aren’t fascinated unless it?s one thing to accomplish with Lady gaga! Your own stuffs great. Always maintain it up!

發佈留言

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