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

  1. I?d need to examine with you here. Which is not one thing I usually do! I get pleasure from studying a submit that will make people think. Additionally, thanks for allowing me to remark!

  2. hello!,I like your writing so much! share we communicate more about your post on AOL? I require an expert on this area to solve my problem. Maybe that’s you! Looking forward to see you.

  3. It?s really a great and useful piece of information. I?m glad that you shared this helpful info with us. Please keep us up to date like this. Thanks for sharing.

  4. One thing I’d prefer to touch upon is that fat reduction plan fast may be possible by the correct diet and exercise. People’s size not just affects the look, but also the entire quality of life. Self-esteem, depressive disorder, health risks, plus physical ability are influenced in extra weight. It is possible to do everything right and at the same time having a gain. If this happens, a medical problem may be the root cause. While excessive food and never enough exercising are usually accountable, common health conditions and traditionally used prescriptions can easily greatly enhance size. Kudos for your post here.

  5. безопасно,
    Лучшие стоматологи города, для крепких и здоровых зубов,
    Специализированная помощь по доступным ценам, для вашей улыбки,
    Бесплатная консультация и диагностика, для вашего комфорта и уверенности,
    Комплексное восстановление утраченных зубов, для вашего долгосрочного удовлетворения,
    Экстренная помощь в любое время суток, для вашего комфорта и удовлетворения,
    Индивидуальный план лечения для каждого пациента, для вашего здоровья и благополучия
    дитяча стоматологічна дитяча стоматологічна .

  6. It is indeed my belief that mesothelioma is actually the most dangerous cancer. It’s got unusual characteristics. The more I look at it the more I am convinced it does not act like a true solid tissues cancer. When mesothelioma is actually a rogue viral infection, so there is the chance of developing a vaccine and also offering vaccination to asbestos open people who are at high risk of developing long term asbestos connected malignancies. Thanks for giving your ideas on this important ailment.

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

  8. I have recently started a blog, the information you offer on this site has helped me tremendously. Thanks for all of your time & work.

  9. This design is wicked! You most certainly know how to keep a reader entertained. Between your wit and your videos, I was almost moved to start my own blog (well, almost…HaHa!) Wonderful job. I really loved what you had to say, and more than that, how you presented it. Too cool!

  10. I’m blown away by the quality of this content! The author has undoubtedly put a huge amount of effort into exploring and structuring the information. It’s refreshing to come across an article that not only provides helpful information but also keeps the readers hooked from start to finish. Hats off to him for producing such a remarkable piece!

  11. An interesting discussion is value comment. I feel that you need to write extra on this matter, it won’t be a taboo subject but typically individuals are not enough to speak on such topics. To the next. Cheers

  12. Thanks for the diverse tips contributed on this website. I have realized that many insurance carriers offer buyers generous savings if they elect to insure a couple of cars with them. A significant number of households own several cars or trucks these days, specially those with mature teenage young children still located at home, along with the savings for policies can soon begin. So it makes sense to look for a great deal.

  13. Hello! I’ve been following your website for a while now and finally got the bravery to go ahead and give you a shout out from Atascocita Texas! Just wanted to mention keep up the good job!

  14. It is appropriate time to make a few plans for the longer term and it’s time to be happy. I have learn this post and if I may I wish to recommend you few fascinating issues or tips. Maybe you can write next articles relating to this article. I wish to learn even more things approximately it!

  15. Eu recomendo um cassino confiavel Blaze

  16. Excelente cassino para ganhos Blaze

  17. Hello would you mind letting me know which webhost you’re using? I’ve loaded your blog in 3 different internet browsers and I must say this blog loads a lot faster then most. Can you recommend a good web hosting provider at a reasonable price? Cheers, I appreciate it!

  18. Thanks for sharing your ideas on this blog. Likewise, a fairy tale regarding the banking institutions intentions whenever talking about foreclosed is that the standard bank will not getreceive my installments. There is a fair bit of time that this bank is going to take payments from time to time. If you are also deep inside hole, they will commonly demand that you pay the particular payment 100 . However, i am not saying that they will have any sort of payments at all. If you and the standard bank can be capable to work something out, a foreclosure method may end. However, in the event you continue to neglect payments beneath new approach, the property foreclosures process can pick up from where it left off.

  19. Hey there would you mind letting me know which web host you’re utilizing? I’ve loaded your blog in 3 completely different web browsers and I must say this blog loads a lot faster then most. Can you suggest a good internet hosting provider at a honest price? Kudos, I appreciate it!

  20. I loved as much as you’ll receive carried out right here. The sketch is tasteful, your authored material stylish. nonetheless, you command get bought an impatience over that you wish be delivering the following. unwell unquestionably come more formerly again as exactly the same nearly very often inside case you shield this increase.

  21. Hello there, just became aware of your blog through Google, and found that it’s truly informative. I am going to watch out for brussels. I?ll be grateful if you continue this in future. Numerous people will be benefited from your writing. Cheers!

  22. Um otimo cassino para ganhar Blaze

  23. O lugar perfeito para jogos de azar Blaze

  24. Отличный сайт! Всем рекомендую!Ремонт холодильников на дому

  25. Lewisslund表示:

    Hey! This is kind of off topic but I need some advice from an established blog. Is it very hard to set up your own blog? I’m not very techincal but I can figure things out pretty fast. I’m thinking about creating my own but I’m not sure where to start. Do you have any tips or suggestions? Many thanks

    http://www.cleancenter.net/support.htmВ 
    mail.webco.by/forum/viewtopic.php?p=210334В 
    mysoccerex.com/tag/football-club/В 
    pedlamrisk.com/page4.htmВ 
    avtorasklad.ru/index.php?did=33&le_categoryID=0&page=67&show_all=yesВ 

  26. Eu recomendo o melhor cassino Blaze

  27. Отличный сайт! Всем рекомендую!Ремонт холодильников

發佈留言

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