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

15,579 Responses

  1. It’s a pity you don’t have a donate button! I’d most certainly donate to this superb blog! I suppose for now i’ll settle for bookmarking and adding your RSS feed to my Google account. I look forward to new updates and will share this site with my Facebook group. Chat soon!

  2. PatrickLef表示:

    alternativa al viagra senza ricetta in farmacia: viagra prezzo – viagra ordine telefonico

  3. Если вы искали где отремонтировать сломаную технику, обратите внимание – ремонт цифровой техники уфа

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

  5. F*ckin? remarkable things here. I?m very glad to see your article. Thanks a lot and i’m looking forward to contact you. Will you kindly drop me a mail?

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

  7. Hey! This is my first visit to your blog! We are a team of volunteers and starting a new project in a community in the same niche. Your blog provided us valuable information to work on. You have done a marvellous job!

  8. Kennethtub表示:

    https://sildenafilit.pro/# viagra originale recensioni
    comprare farmaci online con ricetta

  9. Thanks for the post. My spouse and i have always observed that many people are desirous to lose weight as they wish to appear slim plus attractive. Nonetheless, they do not continually realize that there are many benefits just for losing weight as well. Doctors state that overweight people have problems with a variety of disorders that can be perfectely attributed to their particular excess weight. Thankfully that people who definitely are overweight in addition to suffering from diverse diseases are able to reduce the severity of their particular illnesses by simply losing weight. You possibly can see a constant but identifiable improvement in health if even a negligible amount of fat loss is accomplished.

  10. I love your blog.. very nice colors & theme. Did you design this website yourself or did you hire someone to do it for you? Plz reply as I’m looking to design my own blog and would like to find out where u got this from. appreciate it

  11. MichaelToP表示:

    acquisto farmaci con ricetta Brufen antinfiammatorio farmacie online autorizzate elenco

  12. online ro表示:

    There is noticeably a bundle to know about this. I assume you made sure nice points in features also.

  13. Howdy just wanted to give you a quick heads up. The words in your article seem to be running off the screen in Firefox. I’m not sure if this is a format issue or something to do with browser compatibility but I thought I’d post to let you know. The layout look great though! Hope you get the issue solved soon. Thanks

  14. LouisFoums表示:

    siti sicuri per comprare viagra online: viagra farmacia – viagra generico sandoz

  15. I have observed that of all forms of insurance, medical insurance is the most debatable because of the clash between the insurance policies company’s obligation to remain afloat and the customer’s need to have insurance policies. Insurance companies’ earnings on wellbeing plans are extremely low, thus some businesses struggle to generate income. Thanks for the concepts you reveal through this website.

  16. A few things i have observed in terms of computer system memory is the fact there are technical specs such as SDRAM, DDR and many others, that must match the technical specs of the mother board. If the personal computer’s motherboard is rather current and there are no operating-system issues, modernizing the memory space literally normally takes under an hour. It’s among the easiest personal computer upgrade types of procedures one can imagine. Thanks for revealing your ideas.

  17. LouisFoums表示:

    farmacia online piГ№ conveniente: Tadalafil generico migliore – farmacia online piГ№ conveniente

  18. LouisFoums表示:

    pillole per erezioni fortissime: viagra farmacia – cialis farmacia senza ricetta

  19. EdwardMet表示:

    acquisto farmaci con ricetta Cialis generico prezzo farmacie online sicure

  20. I think one of your advertisements triggered my internet browser to resize, you may well want to put that on your blacklist.

  21. I was just seeking this info for some time. After six hours of continuous Googleing, finally I got it in your web site. I wonder what’s the lack of Google strategy that don’t rank this kind of informative web sites in top of the list. Normally the top web sites are full of garbage.

  22. Have you ever considered publishing an e-book or guest authoring on other websites? I have a blog based upon on the same information you discuss and would really like to have you share some stories/information. I know my subscribers would value your work. If you are even remotely interested, feel free to shoot me an email.

  23. A person essentially help to make significantly posts I might state. This is the first time I frequented your web page and thus far? I surprised with the analysis you made to make this particular submit extraordinary. Fantastic job!

  24. CharlesrooNo表示:

    viagra originale in 24 ore contrassegno viagra originale in 24 ore contrassegno viagra 50 mg prezzo in farmacia

  25. server ro表示:

    I discovered your blog site on google and test a number of of your early posts. Continue to keep up the superb operate. I simply additional up your RSS feed to my MSN News Reader. Searching for ahead to studying extra from you later on!?

  26. ro iro表示:

    I adore your wordpress template, wherever did you obtain it through?

  27. Edisonanazy表示:

    migliori farmacie online 2024: farmacia online migliore – comprare farmaci online all’estero

  28. CharlesrooNo表示:

    farmacia online senza ricetta Cialis generico 20 mg 8 compresse prezzo comprare farmaci online all’estero

  29. Do you mind if I quote a couple of your posts as long as I provide credit and sources back to your webpage? My blog site is in the exact same area of interest as yours and my visitors would really benefit from some of the information you provide here. Please let me know if this okay with you. Thank you!

發佈留言

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