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

11,226 Responses

  1. An impressive share, I simply given this onto a colleague who was doing a bit evaluation on this. And he in actual fact bought me breakfast as a result of I found it for him.. smile. So let me reword that: Thnx for the treat! But yeah Thnkx for spending the time to debate this, I really feel strongly about it and love reading more on this topic. If potential, as you change into expertise, would you mind updating your blog with more particulars? It is highly helpful for me. Massive thumb up for this weblog submit!

  2. GarrettBic表示:

    Мой Источник Права специализируется на предоставлении всего комплекса юридических услуг от консультаций до ведения сложнейших дел в судах различных инстанций.
    семейный адвокат москва
    Несмотря на молодость компании, специалисты неоднократно доказывали свою компетенцию в решении сложных юридических задач. Помимо консультирования граждан и юридической поддержки компаний, адвокаты осуществляют успешную правовую защиту наших клиентов в суде.

    Основные направления деятельности компании:

    оказание юридических услуг организациям;
    правовая поддержка физических лиц;
    регистрационные действия и ликвидация.
    Каждый специалист имеет специализацию в области права и большой практический опыт. Средний стаж юридической практики наших адвокатов – 20 лет. Гарантией победы в решении сложнейших дел клиентов является грамотный подход, богатый профессиональный и жизненный опыт наших адвокатов. Мы с гордостью отмечаем высокие компетенции специалистов, что подтверждается положительными отзывами наших клиентов и доверительными отношениями с ними.

    Более половины клиентов МИП в дальнейшем регулярно обращаются к нам за юридической консультацией.

    Наши судебные защитники и партнеры находятся в курсе последних изменений в законодательстве, принимают активное участие в жизни юридического сообщества, регулярно выступают на форумах и семинарах перед представителями делового сообщества большой судебный опыт дает нам возможность исключить ошибочные действия при защите клиентов и предусматривать заранее возникновение любых рисков.

    Мы уверены, что выбор адвоката строится на основании доверия к нему, поэтому стремимся не допускать расхождения слов с делом.

  3. I can’t believe how amazing this article is! The author has done a fantastic job of conveying the information in an compelling and informative manner. I can’t thank her enough for providing such valuable insights that have definitely enhanced my knowledge in this subject area. Bravo to her for creating such a work of art!

  4. Hi there just wanted to give you a quick heads up. The text 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 thought I’d post to let you know. The design look great though! Hope you get the issue solved soon. Thanks

  5. 66856032 vk表示:

    I am really enjoying the theme/design of your website. Do you ever run into any web browser compatibility problems? A number of my blog audience have complained about my website not working correctly in Explorer but looks great in Firefox. Do you have any solutions to help fix this problem?

  6. Hi! I just wanted to ask if you ever have any trouble with hackers? My last blog (wordpress) was hacked and I ended up losing many months of hard work due to no back up. Do you have any solutions to protect against hackers?

  7. I?ve learn some good stuff here. Certainly worth bookmarking for revisiting. I surprise how a lot effort you set to make any such excellent informative web site.

  8. Hey! I know this is somewhat off topic but I was wondering which blog platform are you using for this website? I’m getting fed up of WordPress because I’ve had problems with hackers and I’m looking at alternatives for another platform. I would be fantastic if you could point me in the direction of a good platform.

  9. LouisAlubs表示:

    At the end of the day, don’t we all want to be happy? Here are 5 ways to get there
    мюц
    Americans are really into pursuing happiness.

    What happiness means is different for each individual and may shift over a lifetime: joy, love, purpose, money, health, freedom, gratitude, friendship, romance, fulfilling work? All of the above? Something else entirely? Many have even suggested that while we may think we know what will make us happy, we are often wrong.

    One man may have cracked the code for what makes a happy and healthier life — and he has the data to back him up.

    Dr. Robert Waldinger is the director of the Harvard Study of Adult Development — possibly the longest-running longitudinal study on human happiness, which started back in 1938. (The original study followed two groups of males, Harvard College students and adolescents in Boston’s inner city. It was expanded in recent decades to include women and people of more diverse backgrounds.)

    Plenty of components are at play in the quest for a happier life, but the key comes down to one main factor: quality relationships.

    “What we found was that the important thing was to stay actively connected to at least a few people, because we all need a sense of connection to somebody as we go through life,” Waldinger told CNN Chief Medical Correspondent Dr. Sanjay Gupta recently on his podcast Chasing Life.

    “And the people who were connected to other people lived longer and stayed physically healthier than the people who were more isolated,” he said. “That was the surprise in our study: not that people were happier but that they lived longer.”

  10. I do not even know how I finished up here, but I believed this put up used to be good. I do not understand who you’re but definitely you’re going to a famous blogger should you are not already 😉 Cheers!

  11. DouglasGed表示:

    cheap ed: Cheap ED pills online – cheap ed pills

  12. asiansexdiary表示:

    excellent issues altogether, you just received a brand new reader. What might you suggest in regards to your submit that you simply made some days in the past? Any positive?

  13. Diplomi_ihEa表示:

    Привет, друзья!
    Приобрести документ о получении высшего образования вы имеете возможность в нашей компании в столице.
    c953879x.bget.ru/index.php?newsid=6

  14. DouglasGed表示:

    mexican border pharmacies shipping to usa: Certified Mexican pharmacy – reputable mexican pharmacies online

  15. You can definitely see your skills within the work you write. The arena hopes for more passionate writers such as you who are not afraid to say how they believe. At all times follow your heart.

  16. DouglasGed表示:

    Online medicine order: Top mail order pharmacies – indian pharmacy online

  17. I?m impressed, I have to say. Really not often do I encounter a weblog that?s each educative and entertaining, and let me inform you, you might have hit the nail on the head. Your concept is excellent; the issue is something that not sufficient persons are speaking intelligently about. I’m very happy that I stumbled throughout this in my seek for one thing regarding this.

  18. I?ve read several good stuff here. Definitely worth bookmarking for revisiting. I surprise how much effort you put to make such a wonderful informative web site.

  19. I like what you guys are up also. Such clever work and reporting! Keep up the excellent works guys I?ve incorporated you guys to my blogroll. I think it’ll improve the value of my site 🙂

  20. Hello There. I found your blog using msn. This is an extremely well written article. I?ll be sure to bookmark it and return to read more of your useful information. Thanks for the post. I will definitely comeback.

  21. I loved up to you’ll receive performed right here. The cartoon is attractive, your authored subject matter stylish. however, you command get got an shakiness over that you would like be turning in the following. unwell certainly come further in the past once more since exactly the similar nearly a lot ceaselessly within case you protect this increase.

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

  23. Lazrgzf表示:

    Привет, друзья!
    Купить диплом ВУЗа.
    poselki.animetalk.ru/viewtopic.php?id=26051#p39180

  24. Alfredtom表示:

    Юридические услуги от адвокатов и юристов с самым высоким рейтингом
    профессиональный юрист
    Если вам нужна помощь по любым юридическим вопросам в Москве, наша команда высококлассных юристов работает для вас 24 часа в сутки, 7 дней в неделю.
    У нас есть группа экспертов, которые предоставляют консультации и помощь по различным юридическим вопросам: семейные, финансовые или административные. Мы внимательно исследуем Вашу ситуацию и разработаем эффективный план действий по юридической защите. Изучим доказательную базу и подготовим необходимые документы, которые законно решат Ваши юридические трудности. Вы можете связаться с нами по телефону, онлайн или лично, чтобы обсудить проблему.

    Юристы Межрайонной ассоциации Москвы
    Компетентные специалисты, эксперты в различных областях права. Они помогут в решении самых разных юридических проблем:

    защита интересов в суде;
    гражданские дела;
    семейные дела и права ребенка;
    сделки с недвижимостью;
    защита прав потребителей;
    наследственные дела;
    защита в арбитражном суде;
    административные штрафы.
    Стоимость услуги юриста доступна гражданам разных категорий. Мы учитываем Ваши пожелания и поэтому предлагаем гибкие цены. Подробнее о стоимости услуг юристов, вы можете узнать на нашем сайте или по телефону.

    Адвокаты Межрайонной ассоциации Москвы могут помочь Вам положительно решить даже трудно доказуемые ситуации. Например, наши клиенты выигрывали дела, связанные с:
    ДТП;
    взысканием долгов;
    бракоразводными процессами;
    разделом имущества.
    Наши адвокаты лично сопровождают клиентов, представляют интересы на встречах с представителями исполнительных, надзорных и государственных органов, а также в суде.

    Ассоциация адвокатов и юристов Москвы поможет отстоять Ваши права и избежать лишних юридических трудностей. Мы предлагаем доступную и профессиональную юридическую помощь в решении любых сложных правовых вопросов.

  25. Thanks for your write-up. Another issue is that being a photographer consists of not only problems in capturing award-winning photographs but also hardships in establishing the best photographic camera suited to your needs and most especially hardships in maintaining the caliber of your camera. This really is very real and apparent for those photography addicts that are straight into capturing the particular nature’s exciting scenes — the mountains, the particular forests, the particular wild and the seas. Going to these daring places surely requires a dslr camera that can surpass the wild’s nasty areas.

  26. Hello There. I found your blog using msn. This is a very well written article. I will be sure to bookmark it and return to read more of your useful information. Thanks for the post. I?ll definitely comeback.

  27. hey there and thank you for your info ? I?ve definitely picked up something new from right here. I did however expertise a few technical points using this site, as I experienced to reload the site lots of times previous to I could get it to load properly. I had been wondering if your web host is OK? Not that I am complaining, but sluggish loading instances times will very frequently affect your placement in google and could damage your quality score if ads and marketing with Adwords. Anyway I am adding this RSS to my email and could look out for much more of your respective fascinating content. Ensure that you update this again soon..

  28. Hello There. I found your blog using msn. This is a very neatly written article. I will make sure to bookmark it and come back to read more of your useful information. Thank you for the post. I will certainly comeback.

  29. Reent表示:

    veikkaus.fi fi tulokset#! tulokset keno Lisäjännitystä peliin saa valitsemalla KuningasKenon, jossa lisämaksua vastaan voi lisätä voittokertoimia. Tällöin on mahdollista korottaa voittosummaa kertoimien avulla. Toisaalta on mahdollista valita myös erilaisia pelipaketteja sekä pelata järjestelmäpeliä. Keno tulos määräytyy kenotason, kertoimien ja voittoluokan perusteella. Voittotulos saadaan kertomalla panos kenon kertoimella. Keno kertoimet ja voittoluokat on helppo tarkistaa Veikkauksen nettisivuilta. Taulukoita voi halutessaan tutkia myös omaa pelistrategiaa miettiessä.
    https://datenportal.prosper-ro.auf.uni-rostock.de/user/sesdotano1986
    Se, mikä näissä Pay N Play -kasinoissa viehättää on ehkä mysteeri muiden maiden pelaajille, mutta mitäpä se meitä haittaa. Kaikilla kasinoilla, jotka tarjoavat pelaajilleen tämä Talleta ja Pelaa -vaihtoehdon, pääsee pelaamaan ihan yhtä turvallisesti kuin rekisteröitymistä vaativilla, mutta paljon nopeammin. Jos lupaus Pay N Play online casinosta kuulostaa hyvältä, voit klikata tästä ja mennä vilkaisemaan Casinokokemuksen keräämät kasinolistaukset. Näillä listoilla vaatimuksena on, että kasino on turvallinen, korkea laatuinen ja tili vapaa. Basis of this page is in Wikipedia. Text is available under the CC BY-SA 3.0 Unported License. Non-text media are available under their specified licenses. Wikipedia® is a registered trademark of the Wikimedia Foundation, Inc. mgwiki.top is an independent company and has no affiliation with Wikimedia Foundation.

  30. An added important aspect is that if you are an older person, travel insurance intended for pensioners is something that is important to really take into account. The more mature you are, the more at risk you are for permitting something poor happen to you while abroad. If you are not really covered by some comprehensive insurance plan, you could have a few serious complications. Thanks for discussing your guidelines on this blog site.

發佈留言

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