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

  1. Suppose inventory prices have risen above ranges justified by the fundamentals.

  2. The presiding magistrate discovered this fascinating, so execution of the sentence was delayed for a week or two on that point of regulation.

  3. Generally, you possibly can go to NPCs to vary your characters’ strengths or abilities.

  4. Greetings! I know this is kinda off topic however , I’d figured I’d ask. Would you be interested in exchanging links or maybe guest authoring a blog post or vice-versa? My site addresses a lot of the same subjects as yours and I feel we could greatly benefit from each other. If you happen to be interested feel free to send me an e-mail. I look forward to hearing from you! Great blog by the way!

  5. ro malaysia表示:

    Another thing I have really noticed is always that for many people, below-average credit is the reaction to circumstances outside of their control. One example is they may have been saddled through an illness and because of this they have large bills for collections. It could be due to a work loss and the inability to go to work. Sometimes divorce proceedings can truly send the finances in the undesired direction. Thank you for sharing your notions on this website.

  6. The very best strolling shoes for girls will really feel supportive on your specific foot structure and assist decrease the impact on your joints, protect your foot tendons from feeling strained, and lower your chances of developing a stress fracture, which girls are extra prone to, says Elizabeth Daughtry, DPM, FACFAS, podiatrist with Foot & Ankle Specialists of the Mid-Atlantic.

  7. Simply as a machine may harness monumental energies and focus them via a single mechanical part, so too one man arguably turned the fulcrum on which science and, subsequently, Western civilization shifted.

  8. As spring approached, as a substitute of the dark fingers of anxiety that had tapped on the back of my neck for the past 12 months, I started to really feel hopeful for the primary time in a very long time.

  9. Allow us to comply with these municipal kings into their own area: the burden on their shoulders is immense, and much beyond what human strength can help.

  10. Life insurance coverage trusts – If the family is expecting a considerable life insurance coverage policy that could put your net worth in the property-tax zone (estates of almost $5.5 million or more in 2015 for federal taxes; states might tax smaller estates), a life insurance coverage belief can be utilized to take away life insurance assets from the property.

  11. 野鳥冬表示:

    This idea was first proposed in 1974 and was completed in 1976, forming the Leonardville United Methodist Church.

  12. The term “server” can be a misnomer — most MMORPGs require numerous servers.

  13. On a construction site, the PM may be the boss, however he serves two masters: the development company that employs him and the shopper for whom a selected challenge is being built.

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

  15. There were gullies and ravines, and holes like gravel-pits, reduce in ice; lumps and scattered pieces frozen all the way down to the unique ground of the floe; blotches of outdated black ice that had been thrust under the floe in some gale and heaved up again; roundish boulders of ice; saw-like edges of ice carved by the snow that flies before the wind; and sunken pits the place thirty or forty acres lay beneath the extent of the rest of the field.

  16. People, in spite of everything, don’t commerce with monkeys or mice.

  17. We found them impressively durable, with no noticeable wear or odor even after all three take a look at wears.

  18. Journey insurance coverage isn’t included in this Antarctica Classic tour.

  19. When the phrase “résumé” is used to seek advice from a one- or two-page document that summarizes the education, expertise and experience of a possible job candidate, there’s a good likelihood the candidate is writing in American or Canadian English.

  20. POD service companies provide production, printing, and delivery companies, making them the majority of beneficial dropshipping companions.Which Platform is Finest for Print on Demand?

  21. In February 1948, on the initiative of Albert Chaminade (1912-2009), resistant throughout World War marked by the warfare he had a cousin who was killed in the Oradour-sur-Glane, dean of the Medal of Youth, Sports and associative commitment of the Haute-Vienne, Chevalier of the Legion of Honour which was abdicated to it by the President of the Republic Jacques Chirac in 1999, former nationwide and worldwide referee, Politician, Basketball participant whose originating CSP the area, a gathering was organized by basketball participant and politician is promoting a bit basketball: she opposed a selection of Limousin to Hungarian training, which history has not given me the identify, but this to me nevertheless given the anecdotal score of the game (47-28 for choice Limousine).

  22. • Manafication will no longer improve Black Mana and White Mana by 50, and will instead permit the execution of enchanted swordplay actions without price (can now be executed while mana is at 51 or more without waste).

  23. And there you might have it!

  24. This is because some ballet flats are too tight and it may simply offer you blisters if they haven’t been stretch quite a bit.

  25. Wonderful work! This is the kind of info that are meant to be shared across the web. Disgrace on Google for no longer positioning this submit higher! Come on over and seek advice from my web site . Thank you =)

  26. The only thing that places an end to the downward spiral is authorities intervention on a grand scale, socializing the losses which were incurred, and freeing up the surviving institutions to begin lending once more.

  27. Draco hatches a plan to repair it and to make use of it and its twin at Borgin and Burkes to sneak Dying Eaters into Hogwarts.

  28. Teva Common Trail Sandals: These are excellent quality, snug sandals that may doubtless final a very long time.

  29. As you do that, visualize any unfavourable energies being washed away, leaving your crystal cleansed and able to amplify your intentions.

  30. Ecco has a incredible assortment of walking sandals for journey, all of which give great help and are perfect for the model-acutely aware traveler who seeks a steadiness of comfort and style.

發佈留言

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