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

38,174 Responses

  1. Robertfap表示:

    http://tadalmed.com/# Tadalafil 20 mg prix en pharmacie

  2. Kennethedugs表示:

    Of course, he said yes to coming back to the series, which eventually required him to live in Italy for a few months for filming.
    hop protocol
    During production, White revealed to Gries that Greg is “very sinister.” That became rather irrefutable by the season’s climax, which saw Tanya’s demise orchestrated by her now-husband.

    Come Season 3, Gries had to rewrite Greg’s backstory again, this time drawing from some unlikely sources for inspiration, like HBO docuseries “The Jinx,” about late convicted killer Robert Durst, and the case involving the man who came to be known as the Tinder Swindler.

    Gries said he was struck by Durst’s “kind of seemingly even keel personality,” which served as a model for where Greg was headed, someone “who doesn’t really show a great deal of emotion, doesn’t seem to get too angry, just gets a little bit irritated and is dangerous.”

    “There’s a bridled rage underneath. And those kind of people I find – at least with respect to Gary, Greg, Gary – fascinating,” he said.

    And yet, while searching for an empathetic way back to portraying his character, Gries kept wondering if there was anything still redeeming about Greg.
    An important “wake up moment” came during a decisive conversation he had with White just before filming in Thailand, in which the show’s creator said of Greg, in no uncertain terms: “He’s a psychopath.”

    “And that was it. It was like, ‘back to the drawing board.’ And it really did help me,” Gries said.

    The penultimate episode of the series will air on Sunday, an evening that thanks to “Lotus” and other shows has again become a night of appointment viewing amid a general move away from binge watching. Gries said he appreciates the shift.

    “We’re a society that in a weird way doesn’t understand the beauty of waiting. The beauty of the space between the notes,” he shared. “If I binged (‘White Lotus’) I’d feel like I just ate too many chocolates. It just wouldn’t be the same. You need to process this.”

    “The White Lotus” airs Sundays at 9 p.m. EDT on HBO, with the episode available to stream on Max. HBO and Max, like CNN, are owned by the same parent company, Warner Bros. Discovery.

  3. BradleyJaire表示:

    Achat mГ©dicament en ligne fiable: pharmacie en ligne fiable – п»їpharmacie en ligne france pharmafst.com

  4. Bernardshoor表示:

    achat kamagra: kamagra oral jelly – kamagra livraison 24h

  5. Bernardshoor表示:

    kamagra pas cher: Kamagra pharmacie en ligne – Kamagra Commander maintenant

  6. Bernardshoor表示:

    kamagra livraison 24h: achat kamagra – kamagra gel

  7. Peterclada表示:

    trouver un mГ©dicament en pharmacie Medicaments en ligne livres en 24h pharmacie en ligne france livraison belgique pharmafst.shop

  8. BillieLet表示:

    Kamagra pharmacie en ligne: kamagra 100mg prix – Kamagra Oral Jelly pas cher

  9. 58win表示:

    Hi! 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 beneficial information to work on. You have done a marvellous job!

  10. sodo66表示:

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

  11. Peterclada表示:

    cialis generique Cialis sans ordonnance pas cher Cialis en ligne tadalmed.com

  12. sodo66表示:

    Hi, i feel that i saw you visited my site thus i got here to ?return the choose?.I am attempting to to find issues to enhance my site!I suppose its good enough to use some of your concepts!!

  13. BillieLet表示:

    kamagra livraison 24h: Kamagra Commander maintenant – achat kamagra

  14. qq88表示:

    great post, very informative. I wonder why the other experts of this sector do not notice this. You should continue your writing. I am confident, you’ve a great readers’ base already!

  15. 58win表示:

    Thank you for sharing these types of wonderful posts. In addition, the optimal travel along with medical insurance plan can often eliminate those worries that come with traveling abroad. A new medical emergency can quickly become very expensive and that’s sure to quickly decide to put a financial weight on the family finances. Setting up in place the suitable travel insurance package deal prior to leaving is worth the time and effort. Thank you

  16. BradleyJaire表示:

    pharmacie en ligne: Meilleure pharmacie en ligne – pharmacie en ligne fiable pharmafst.com

  17. Уютные шторы для загородного коттеджа
    шторы для коттеджа шторы для коттеджа .

  18. qq88表示:

    Wonderful beat ! I would like to apprentice while you amend your web site, how can i subscribe for a blog site? The account helped me a acceptable deal. I had been a little bit acquainted of this your broadcast provided bright clear concept

  19. sodo66表示:

    I am so happy to read this. This is the type of manual that needs to be given and not the accidental misinformation that is at the other blogs. Appreciate your sharing this best doc.

  20. sodo66表示:

    I have realized that car insurance providers know the cars and trucks which are at risk from accidents and various risks. Additionally , they know what kind of cars are inclined to higher risk plus the higher risk they’ve the higher the premium fee. Understanding the simple basics with car insurance will allow you to choose the right style of insurance policy that will take care of your needs in case you happen to be involved in any accident. Appreciate your sharing the ideas with your blog.

  21. qq88表示:

    Definitely believe that that you stated. Your favourite reason appeared to be on the internet the simplest thing to understand of. I say to you, I definitely get annoyed while people think about issues that they just do not understand about. You managed to hit the nail upon the highest as well as defined out the whole thing without having side effect , folks could take a signal. Will probably be again to get more. Thanks

  22. sodo66表示:

    hey there and thank you for your information ? I have definitely picked up anything new from right here. I did however expertise a few technical issues using this web site, as I experienced to reload the web site many times previous to I could get it to load correctly. I had been wondering if your hosting is OK? Not that I am complaining, but sluggish loading instances times will sometimes affect your placement in google and could damage your high-quality score if advertising and marketing with Adwords. Well I?m adding this RSS to my email and can look out for a lot more of your respective fascinating content. Make sure you update this again soon..

  23. BradleyJaire表示:

    cialis sans ordonnance: Acheter Cialis 20 mg pas cher – Acheter Cialis 20 mg pas cher tadalmed.shop

  24. sodo66表示:

    I’m blown away by the quality of this content! The author has clearly put a huge amount of effort into investigating and structuring the information. It’s inspiring to come across an article that not only offers valuable information but also keeps the readers captivated from start to finish. Hats off to her for creating such a remarkable piece!

  25. EdwardGraby表示:

    New design revealed for Airbus hydrogen plane
    beefy fi
    In travel news this week: Bhutan’s spectacular new airport, the world’s first 3D-printed train station has been built in Japan, plus new designs for Airbus’ zero-emission aircraft and France’s next-generation high-speed trains.

    Grand designs
    European aerospace giant Airbus has revealed a new design for its upcoming fully electric, hydrogen-powered ZEROe aircraft. powered by hydrogen fuel cells.

    The single-aisle plane now has four engines, rather than six, each powered by their own fuel cell stack.

    The reworked design comes after the news that the ZEROe will be in our skies later than Airbus hoped.

    The plan was to launch a zero-emission aircraft by 2035, but now the next-generation single-aisle aircraft is slated to enter service in the second half of the 2030s.

    Over in Asia, the Himalayan country of Bhutan is building a gloriously Zen-like new airport befitting a nation with its very own happiness index.

    Gelephu International is designed to serve a brand new “mindfulness city,” planned for southern Bhutan, near its border with India.

    In rail travel, Japan has just built the world’s first 3D-printed train station, which took just two and a half hours to construct, according to The Japan Times. That’s even shorter than the whizzy six hours it was projected to take.

    France’s high-speed TGV rail service has revealed its next generation of trains, which will be capable of reaching speeds of up to 320 kilometers an hour (nearly 200 mph).

    The stylish interiors have been causing a stir online, as has the double-decker dining car.

    Finally, work is underway in London on turning a mile-long series of secret World War II tunnels under a tube station into a major new tourist attraction. CNN took a look inside.

  26. sodo66表示:

    An attention-grabbing discussion is price comment. I believe that you should write more on this subject, it may not be a taboo topic however typically individuals are not sufficient to speak on such topics. To the next. Cheers

  27. Robertfap表示:

    https://pharmafst.shop/# Pharmacie sans ordonnance

  28. sodo66表示:

    wonderful post, very informative. I wonder why the other specialists of this sector do not notice this. You must continue your writing. I’m confident, you’ve a great readers’ base already!

  29. 58win表示:

    I know this if off topic but I’m looking into starting my own weblog and was wondering what all is required to get set up? I’m assuming having a blog like yours would cost a pretty penny? I’m not very internet smart so I’m not 100 certain. Any tips or advice would be greatly appreciated. Thanks

  30. 58win表示:

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

發佈回覆給「sodo66」的留言 取消回覆

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