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

  1. наркологическая скорая бесплатная [url=http://www.skoraya-narkologicheskaya-pomoshch16.ru]наркологическая скорая бесплатная [/url] .

  2. Interesting post here. One thing I would really like to say is the fact that most professional areas consider the Bachelor’s Degree just as the entry level standard for an online diploma. Whilst Associate Diplomas are a great way to get started, completing the Bachelors presents you with many doorways to various occupations, there are numerous online Bachelor Diploma Programs available by institutions like The University of Phoenix, Intercontinental University Online and Kaplan. Another issue is that many brick and mortar institutions make available Online versions of their diplomas but generally for a extensively higher payment than the providers that specialize in online course programs.

  3. неотложная наркологическая помощь в москве https://skoraya-narkologicheskaya-pomoshch16.ru .

  4. неотложная наркологическая помощь в москве [url=www.skoraya-narkologicheskaya-pomoshch15.ru/]www.skoraya-narkologicheskaya-pomoshch15.ru/[/url] .

  5. ArthurKib表示:

    http://indianpharmacy.company/# top 10 online pharmacy in india

  6. ArthurKib表示:

    https://pharmbig24.online/# generic cialis uk online pharmacy

  7. pure cbd oil表示:

    This article is absolutely incredible! The author has done a phenomenal job of conveying the information in an compelling and informative manner. I can’t thank him enough for sharing such precious insights that have definitely enhanced my knowledge in this topic. Kudos to her for crafting such a masterpiece!

  8. RobertMef表示:

    indian pharmacy online: pharmacy website india – indian pharmacy online

  9. Профессиональный сервисный центр по ремонту бытовой техники с выездом на дом.
    Мы предлагаем: ремонт крупногабаритной техники в москве
    Наши мастера оперативно устранят неисправности вашего устройства в сервисе или с выездом на дом!

  10. Hi my friend! I wish to say that this article is awesome, nice written and include almost all significant infos. I?d like to see more posts like this.

  11. Josephfub表示:

    medicine in mexico pharmacies п»їbest mexican online pharmacies medicine in mexico pharmacies

  12. RobertMef表示:

    buy prescription drugs from india: п»їlegitimate online pharmacies india – online pharmacy india

  13. Josephfub表示:

    pharmacy cost viagra shoprite pharmacy shoprite pharmacy

  14. скорая наркологическая помощь на дому в москве https://www.skoraya-narkologicheskaya-pomoshch12.ru .

  15. I have figured out some new issues from your web site about computer systems. Another thing I have always assumed is that laptop computers have become a specific thing that each family must have for some reasons. They provide convenient ways in which to organize households, pay bills, search for information, study, listen to music and perhaps watch tv shows. An innovative solution to complete many of these tasks is by using a notebook computer. These computers are portable ones, small, powerful and lightweight.

  16. Hey there this is kinda of off topic but I was wanting to know if blogs use WYSIWYG editors or if you have to manually code with HTML. I’m starting a blog soon but have no coding expertise so I wanted to get advice from someone with experience. Any help would be greatly appreciated!

  17. ArthurKib表示:

    http://indianpharmacy.company/# Online medicine home delivery

  18. Отличный сайт! Всем рекомендую!slivkursov.net

  19. Your website doesn’t display correctly on my iphone 4 – you may wanna try and fix that

  20. I?ll right away seize your rss feed as I can not in finding your email subscription hyperlink or newsletter service. Do you have any? Please permit me realize in order that I may just subscribe. Thanks.

  21. Hello! Someone in my Myspace group shared this site with us so I came to give it a look. I’m definitely enjoying the information. I’m book-marking and will be tweeting this to my followers! Excellent blog and excellent design and style.

  22. RobertMef表示:

    mexican rx online: best online pharmacies in mexico – buying from online mexican pharmacy

  23. Thanks for your write-up. One other thing is when you are advertising your property all on your own, one of the concerns you need to be cognizant of upfront is how to deal with house inspection reviews. As a FSBO vendor, the key to successfully shifting your property and also saving money in real estate agent revenue is awareness. The more you realize, the easier your home sales effort is going to be. One area where this is particularly significant is inspection reports.

  24. MauriceGueda表示:

    illegal online pharmacy: asda pharmacy fluconazole – online pharmacy without prescriptions

  25. MauriceGueda表示:

    п»їlegitimate online pharmacies india: reputable indian pharmacies – indian pharmacy paypal

  26. Thx for your post. I want to comment that the tariff of car insurance varies from one insurance policy to another, simply because there are so many different issues which play a role in the overall cost. For example, the make and model of the car will have a tremendous bearing on the price. A reliable ancient family automobile will have a more economical premium compared to a flashy expensive car.

  27. Thank you, I’ve been searching for facts about this topic for ages and yours is the best I have found so far.

  28. MauriceGueda表示:

    mens ed pills: online pharmacy anabolic steroids – viagra local pharmacy

  29. Hey there just wanted to give you a quick heads up. The words in your post seem to be running off the screen in Internet explorer. I’m not sure if this is a formatting issue or something to do with web browser compatibility but I figured I’d post to let you know. The layout look great though! Hope you get the problem resolved soon. Thanks

發佈留言

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