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

  1. Greetings I am so grateful I found your website, I really found you by mistake, while I was browsing on Yahoo for something else, Anyhow I am here now and would just like to say thanks for a fantastic post and a all round entertaining blog (I also love the theme/design), I don’t have time to browse it all at the moment but I have saved it and also added your RSS feeds, so when I have time I will be back to read much more, Please do keep up the fantastic work.

  2. Have you ever thought about writing an ebook or guest authoring on other sites? I have a blog centered on the same information you discuss and would love to have you share some stories/information. I know my viewers would value your work. If you’re even remotely interested, feel free to send me an e-mail.

  3. Howdy! I’m at work surfing around your blog from my new iphone 3gs! Just wanted to say I love reading your blog and look forward to all your posts! Keep up the great work!

  4. TomasRop表示:

    Farmacia online piГ№ conveniente: sildenafil oral jelly 100mg kamagra – Farmacia online piГ№ conveniente

  5. As I site possessor I believe the content matter here is rattling magnificent , appreciate it for your hard work. You should keep it up forever! Best of luck.

  6. Hello There. I found your blog using msn. This is a really well written article. I?ll make sure to bookmark it and come back to read more of your useful info. Thanks for the post. I?ll definitely return.

  7. RandyLunda表示:

    farmacie online autorizzate elenco: kamagra gel – farmacia online senza ricetta

  8. RandyLunda表示:

    cerco viagra a buon prezzo: viagra subito – viagra 50 mg prezzo in farmacia

  9. Thanks for your interesting article. One other problem is that mesothelioma is generally a result of the inhalation of fibres from mesothelioma, which is a very toxic material. It truly is commonly seen among workers in the structure industry who may have long contact with asbestos. It is caused by residing in asbestos insulated buildings for an extended time of time, Genetic makeup plays a crucial role, and some persons are more vulnerable towards the risk as compared with others.

  10. Annett表示:

    Also visit my web-site; Find top-rated certified Daycares in your area
    (Annett)

  11. RandyLunda表示:

    farmacia senza ricetta recensioni: viagra prezzo – cialis farmacia senza ricetta

  12. By my observation, shopping for consumer electronics online may be easily expensive, nevertheless there are some tips and tricks that you can use to obtain the best products. There are often ways to obtain discount offers that could make one to come across the best electronics products at the smallest prices. Interesting blog post.

  13. Very nice post. I just stumbled upon your weblog and wanted to say that I’ve truly enjoyed browsing your blog posts. In any case I will be subscribing to your feed and I hope you write again very soon!

  14. After I initially commented I clicked the -Notify me when new comments are added- checkbox and now every time a remark is added I get four emails with the identical comment. Is there any means you possibly can remove me from that service? Thanks!

  15. It?s onerous to seek out educated people on this topic, but you sound like you understand what you?re talking about! Thanks

  16. Greetings! I know this is somewhat off topic but I was wondering if you knew where I could find a captcha plugin for my comment form? I’m using the same blog platform as yours and I’m having trouble finding one? Thanks a lot!

  17. TomasRop表示:

    top farmacia online: Farmacia online migliore – Farmacia online miglior prezzo

  18. Timothyzew表示:

    http://avanafil.pro/# farmacie online sicure

  19. Nice post. I be taught something tougher on totally different blogs everyday. It would always be stimulating to read content material from different writers and practice just a little something from their store. I?d desire to make use of some with the content on my blog whether you don?t mind. Natually I?ll offer you a hyperlink in your net blog. Thanks for sharing.

  20. you’re in reality a good webmaster. The web site loading speed is incredible. It sort of feels that you are doing any unique trick. In addition, The contents are masterwork. you have performed a magnificent task in this topic!

  21. Thanks for the ideas shared on your own blog. Something else I would like to convey is that fat reduction is not all about going on a celebrity diet and trying to get rid of as much weight as you can in a few days. The most effective way to shed weight is by getting it little by little and obeying some basic tips which can provide help to make the most out of your attempt to shed weight. You may recognize and be following a few of these tips, but reinforcing know-how never does any damage.

  22. What i don’t realize is actually how you are no longer really a lot more neatly-favored than you might be right now. You’re very intelligent. You recognize therefore significantly relating to this subject, produced me in my opinion consider it from so many varied angles. Its like men and women are not involved except it?s one thing to do with Lady gaga! Your personal stuffs outstanding. All the time handle it up!

  23. I would like to add when you do not currently have an insurance policy or maybe you do not participate in any group insurance, you could well really benefit from seeking aid from a health broker. Self-employed or individuals with medical conditions commonly seek the help of the health insurance specialist. Thanks for your short article.

  24. Your home is valueble for me. Thanks!?

  25. I can’t express how much I admire the effort the author has put into producing this remarkable piece of content. The clarity of the writing, the depth of analysis, and the plethora of information offered are simply impressive. Her passion for the subject is apparent, and it has definitely resonated with me. Thank you, author, for sharing your insights and enhancing our lives with this extraordinary article!

  26. Mazrrpf表示:

    Привет, друзья!
    Сколько стоит диплом высшего и среднего образования и как его получить?
    rushkadiplomik.ru

  27. Italy Tours表示:

    Hi! This is my first visit to your blog! We are a collection of volunteers and starting a new initiative in a community in the same niche. Your blog provided us valuable information to work on. You have done a extraordinary job!

  28. One thing I’d really like to say is the fact car insurance cancellations is a dreadful experience and if you are doing the appropriate things being a driver you simply won’t get one. Some individuals do obtain notice that they’ve been officially dumped by their insurance company they have to fight to get added insurance after having a cancellation. Low-cost auto insurance rates tend to be hard to get after a cancellation. Understanding the main reasons pertaining to auto insurance cancellations can help people prevent getting rid of in one of the most crucial privileges obtainable. Thanks for the tips shared by your blog.

  29. Thanks for the sensible critique. Me & my neighbor were just preparing to do a little research on this. We got a grab a book from our area library but I think I learned more from this post. I am very glad to see such fantastic information being shared freely out there.

發佈留言

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