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

  1. Robertfap表示:

    https://pharmafst.com/# acheter mГ©dicament en ligne sans ordonnance

  2. BillieLet表示:

    Achetez vos kamagra medicaments: kamagra gel – kamagra oral jelly

  3. sodo66表示:

    Nice post. I study something more challenging on completely different blogs everyday. It is going to always be stimulating to learn content from different writers and observe slightly one thing from their store. I?d want to make use of some with the content material on my weblog whether you don?t mind. Natually I?ll provide you with a hyperlink in your net blog. Thanks for sharing.

  4. sodo66表示:

    After study a number of of the blog posts in your web site now, and I really like your approach of blogging. I bookmarked it to my bookmark web site record and will likely be checking back soon. Pls try my site as nicely and let me know what you think.

  5. qq88表示:

    I haven?t checked in here for some time as I thought it was getting boring, but the last several posts are great quality so I guess I will add you back to my everyday bloglist. You deserve it my friend 🙂

  6. qq88表示:

    Does your website have a contact page? I’m having trouble locating it but, I’d like to shoot you an e-mail. I’ve got some recommendations for your blog you might be interested in hearing. Either way, great blog and I look forward to seeing it develop over time.

  7. sodo66表示:

    Just desire to say your article is as astounding. The clarity in your post is just nice and i can assume you are an expert on this subject. Fine with your permission allow me to grab your feed to keep up to date with forthcoming post. Thanks a million and please keep up the rewarding work.

  8. sodo66表示:

    It’s perfect time to make some plans for the future and it is time to be happy. I have read this post and if I could I desire to suggest you some interesting things or advice. Maybe you can write next articles referring to this article. I wish to read more things about it!

  9. sodo66表示:

    My brother suggested I may like this blog. He was totally right. This post actually made my day. You cann’t believe just how so much time I had spent for this information! Thanks!

  10. qq88表示:

    Hello, i think that i saw you visited my website thus i got here to ?go back the want?.I am attempting to to find things to enhance my website!I assume its ok to use some of your ideas!!

  11. qq88表示:

    Hmm it looks like your site ate my first comment (it was extremely long) so I guess I’ll just sum it up what I submitted and say, I’m thoroughly enjoying your blog. I too am an aspiring blog blogger but I’m still new to everything. Do you have any helpful hints for rookie blog writers? I’d definitely appreciate it.

  12. Peterclada表示:

    acheter mГ©dicament en ligne sans ordonnance pharmacie en ligne sans ordonnance pharmacie en ligne fiable pharmafst.shop

  13. BillieLet表示:

    Kamagra Commander maintenant: acheter kamagra site fiable – acheter kamagra site fiable

  14. BradleyJaire表示:

    п»їpharmacie en ligne france: pharmacie en ligne – pharmacie en ligne france fiable pharmafst.com

  15. Masteroio表示:

    Чат с психологом в телеге. Телеграм психолог. Психолог оказывает помощь онлайн в чате. оценили 3220 раз

  16. BradleyJaire表示:

    Cialis sans ordonnance 24h: Achat Cialis en ligne fiable – cialis sans ordonnance tadalmed.shop

  17. Robertfap表示:

    https://pharmafst.com/# acheter mГ©dicament en ligne sans ordonnance

  18. Robertfap表示:

    https://kamagraprix.com/# Acheter Kamagra site fiable

  19. BillieLet表示:

    pharmacie en ligne fiable: pharmacie en ligne sans ordonnance – pharmacie en ligne pharmafst.com

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

  21. BillieLet表示:

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

  22. Javiercok表示:

    Где покупать технику? лучшие магазины техники рейтинг: проверенные продавцы, акции, удобная доставка и реальный опыт покупателей. Обновляем регулярно.

  23. BradleyJaire表示:

    cialis generique: Acheter Cialis – Pharmacie en ligne Cialis sans ordonnance tadalmed.shop

  24. Индивидуальный пошив штор, эксклюзивный пошив штор..
    Создайте уникальный интерьер с пошивом штор, с гарантией качества..
    Эксклюзивные решения в пошиве штор, по индивидуальному проекту..
    Дизайнерские шторы на заказ, закажите онлайн..
    Профессиональный пошив штор с монтажом, под ключ..
    Пошив штор премиум-класса, по индивидуальному заказу..
    Создаем шторы мечты, Позвольте нам помочь..
    Шторы на любой вкус и цвет, по вашему стилю..
    Эксклюзивные шторы на заказ, для элитных интерьеров..
    Выберите качественный пошив штор, звоните прямо сейчас..
    Пошив штор высокого качества, гарантия соответствия..
    Разнообразие тканей и стилей, по индивидуальному дизайну..
    Пошив штор с профессиональным монтажом, от профессионалов..
    Индивидуальный дизайн штор, по вашим требованиям..
    Качественные шторы на заказ, с современными технологиями..
    Лучшие ткани для пошива штор, по вашему стилю..
    Создаем шторы, которые преобразят ваш интерьер, с бесплатной консультацией..
    пошив штор пошив штор . “Ткацкий”

  25. BradleyJaire表示:

    kamagra en ligne: Achetez vos kamagra medicaments – Kamagra pharmacie en ligne

  26. Robertfap表示:

    https://pharmafst.com/# pharmacie en ligne france livraison internationale

  27. Robertfap表示:

    https://kamagraprix.shop/# Kamagra pharmacie en ligne

  28. BillieLet表示:

    Pharmacie en ligne livraison Europe: Pharmacies en ligne certifiees – pharmacie en ligne france fiable pharmafst.com

  29. Jamesalulk表示:

    ‘For the public to enjoy’
    [url=https://kepir-app.com]keplr wallet[/url]
    The museum’s history starts in 1998, when Sheikh Faisal Bin Qassim Al Thani opened a building to the public on his farm some 20 kilometers (12 miles) north of Qatari capital Doha.

    A distant relative of Qatar’s ruling family, founder and chairman of Al Faisal Holdings (one of Qatar’s biggest conglomerates), and a billionaire whose business acumen had him recognized as one of the most influential Arab businessmen in the world, Sheikh Faisal had already amassed a substantial private collection of historically important regional artifacts, plus a few quirky pieces of interest, allowing visitors an intimate look into Qatari life and history.

    In an interview with Qatari channel Alrayyan TV in 2018, Sheikh Faisal said that the museum started as a hobby.

    “I used to collect items whenever I got the chance,” he said. “As my business grew, so did my collections, and soon I was able to collect more and more items until I decided to put them in the museum for the public to enjoy.”

    His private cabinet of curiosities has since evolved into a 130-acre complex. Through the fort-like entrance gate lies an oryx reserve, an impressive riding school and stables, a duck pond and a mosque built with a quirky leaning minaret. There’s now even a five-star Marriott hotel, two cafes and the Zoufa restaurant serving modern Lebanese cuisine.

    Of course, there’s also the super-sized museum, with a recently-opened car collection housing everything from vintage Rolls-Royces to wartime Jeeps and colorful Buicks. Outside you’ll find peacocks roaming the grounds, and signs warning drivers to be aware of horses and ostriches.

    Visitors to the FBQ museum are free to explore the grounds and can even enter the stables to pat the horses.

  30. ScottTaw表示:

    Iceberg flotillas
    debridge
    Located on the west coast, Ilulissat is a pretty halibut- and prawn-fishing port on a dark rock bay where visitors can sit in pubs sipping craft beers chill-filtered by 100,000-year-old glacial ice.

    It’s a place to be awed by the UNESCO World Heritage Icefjord where Manhattan skyscraper-sized icebergs disgorge from Greenland’s icecap to float like ghostly ships in the surrounding Disko Bay.

    Small boats take visitors out to sail closely among the bay’s magnificent iceberg flotilla. But not too close.

    “I was on my boat once and saw one of these icebergs split in two. The pieces fell backwards into the sea and created a giant wave,” said David Karlsen, skipper of the pleasure-boat, Katak. “…I didn’t hang around.”

    Disko Bay’s other giants are whales. From June to September breaching humpback whales join the likes of fin and minke whales feasting on plankton. Whale-watching is excellent all around Greenland’s craggy coastline.

    Whales are eaten here. Visitors shouldn’t be surprised to encounter the traditional Greenlandic delicacy of mattak — whale-skin and blubber that when tasted is akin to chewing on rubber. Inuit communities have quotas to not only hunt the likes of narwhals but also polar bears, musk-ox and caribou — which can also appear on menus.

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

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