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

  1. Greetings from Los angeles! I’m bored to tears at work so I decided to check out your website on my iphone during lunch break. I love the info you provide 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 .. Anyhow, superb site!

  2. I like what you guys are up too. Such smart work and reporting! Carry on the superb works guys I?ve incorporated you guys to my blogroll. I think it will improve the value of my site 🙂

  3. Hi there! I’m at work surfing around your blog from my new iphone 3gs! Just wanted to say I love reading through your blog and look forward to all your posts! Carry on the fantastic work!

  4. Write more, thats all I have to say. Literally, it seems as though you relied on the video to make your point. You clearly know what youre talking about, why throw away your intelligence on just posting videos to your weblog when you could be giving us something informative to read?

  5. Excellent read, I just passed this onto a friend who was doing some research on that. And he actually bought me lunch because I found it for him smile So let me rephrase that: Thank you for lunch!

  6. I also believe that mesothelioma is a exceptional form of many forms of cancer that is commonly found in those previously familiar with asbestos. Cancerous cells form while in the mesothelium, which is a protective lining that covers a lot of the body’s areas. These cells ordinarily form in the lining with the lungs, tummy, or the sac which encircles one’s heart. Thanks for expressing your ideas.

  7. Thanks for giving your ideas. I’d also like to express that video games have been ever before evolving. Technology advances and enhancements have made it simpler to create practical and fun games. These kind of entertainment games were not actually sensible when the concept was first of all being attempted. Just like other kinds of technological innovation, video games as well have had to grow as a result of many decades. This is testimony for the fast growth of video games.

  8. noomay69 xxx表示:

    Hi there! This is kind of off topic but I need some advice from an established blog. Is it very difficult 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 begin. Do you have any points or suggestions? Thanks

  9. Hello There. I found your weblog the use of msn. This is a really smartly written article. I will make sure to bookmark it and return to learn more of your helpful information. Thanks for the post. I?ll definitely return.

  10. I’m truly enjoying the design and layout of your site. It’s a very easy on the eyes which makes it much more pleasant for me to come here and visit more often. Did you hire out a designer to create your theme? Exceptional work!

  11. hi!,I like your writing so so much! percentage we keep in touch extra approximately your article on AOL? I require an expert on this house to unravel my problem. May be that is you! Taking a look ahead to look you.

  12. Great goods from you, man. I have understand your stuff previous to and you are just extremely wonderful. I actually like what you’ve acquired here, certainly like what you’re saying and the way in which you say it. You make it enjoyable and you still care for to keep it sensible. I can’t wait to read much more from you. This is really a great website.

  13. vk kantuser_2表示:

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

  14. Trefwqo表示:

    Добрый день!
    Можно ли купить аттестат о среднем образовании? Основные рекомендации
    u0382101.isp.regruhosting.ru/index.php/forum/general-questions-and-how-tos/23070-zarabotok-m406h
    Рады помочь!.

  15. индийские карты гадание https://indiyskiy-pasyans-online.ru .

  16. Attractive section of content. I just stumbled upon your weblog and in accession capital to assert that I acquire actually enjoyed account your blog posts. Any way I will be subscribing to your feeds and even I achievement you access consistently quickly.

  17. xxxปวช1表示:

    fantastic points altogether, you simply gained a brand new reader. What would you recommend about your post that you made some days ago? Any positive?

  18. I believe that avoiding ready-made foods is a first step to help lose weight. They will often taste very good, but ready-made foods contain very little nutritional value, making you take in more just to have enough vigor to get over the day. Should you be constantly feeding on these foods, converting to whole grain products and other complex carbohydrates will help you have more strength while feeding on less. Interesting blog post.

  19. This article is a refreshing change! The author’s unique perspective and thoughtful analysis have made this a truly engrossing read. I’m appreciative for the effort he has put into producing such an informative and thought-provoking piece. Thank you, author, for providing your expertise and igniting meaningful discussions through your outstanding writing!

  20. jjsexkk表示:

    I feel that is among the most significant info for me. And i’m satisfied reading your article. However want to statement on few common issues, The website taste is ideal, the articles is in reality nice : D. Good activity, cheers

  21. Thanks for the useful information on credit repair on your blog. The thing I would offer as advice to people is always to give up this mentality they can buy currently and pay back later. As a society most people tend to make this happen for many things. This includes trips, furniture, and items we’d like. However, it is advisable to separate your wants from all the needs. If you are working to raise your credit score you have to make some sacrifices. For example you’ll be able to shop online to economize or you can look at second hand retailers instead of costly department stores intended for clothing.

  22. 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 shakiness over that you wish be delivering the following. unwell unquestionably come further formerly again as exactly the same nearly very often inside case you shield this increase.

  23. immokaarst表示:

    I have seen a lot of useful items on your web-site about pcs. However, I have got the impression that netbooks are still not nearly powerful adequately to be a good selection if you frequently do tasks that require a great deal of power, such as video editing. But for net surfing, statement processing, and many other typical computer work they are all right, provided you do not mind the little screen size. Many thanks sharing your notions.

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

  25. Thank you for another excellent post. The place else may just anyone get that type of information in such an ideal method of writing? I have a presentation subsequent week, and I’m at the look for such info.

  26. We’re a group of volunteers and opening a new scheme in our community. Your site offered us with valuable information to work on. You have done a formidable job and our entire community will be thankful to you.

  27. What an informative and meticulously-researched article! The author’s thoroughness and aptitude to present complex ideas in a comprehensible manner is truly admirable. I’m extremely enthralled by the scope of knowledge showcased in this piece. Thank you, author, for offering your knowledge with us. This article has been a real game-changer!

  28. One other thing I would like to express is that in lieu of trying to suit all your online degree tutorials on times that you conclude work (since most people are drained when they get home), try to obtain most of your lessons on the week-ends and only one or two courses for weekdays, even if it means a little time off your weekend break. This is beneficial because on the week-ends, you will be much more rested along with concentrated upon school work. Thanks a bunch for the different suggestions I have realized from your blog site.

發佈留言

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