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

10,956 Responses

  1. Casa de apostas com pagamentos maximos Fortune Tiger

  2. Отличный сайт! Рекомендую заглянуть тудаСтроительный консалтинг

  3. EdwardGROOM表示:

    pharmacies en ligne certifiГ©es: kamagra en ligne – acheter mГ©dicament en ligne sans ordonnance

  4. Vgssxg表示:

    priligy mingle – priligy doze dapoxetine utter

  5. Thanks for your thoughts. One thing really noticed is banks plus financial institutions have in mind the spending routines of consumers and as well understand that many people max outside their credit cards around the getaways. They smartly take advantage of this real fact and then start flooding your inbox and snail-mail box with hundreds of no interest APR credit cards offers just after the holiday season ends. Knowing that when you are like 98 of all American open public, you’ll get at the opportunity to consolidate credit card debt and move balances to 0 interest rates credit cards.

  6. eft cheat表示:

    Hello, i read your blog from time to time and i own a similar one and i was just curious if you get a lot of spam remarks? If so how do you stop it, any plugin or anything you can suggest? I get so much lately it’s driving me crazy so any assistance is very much appreciated.

  7. Allenacurf表示:

    Pharmacie Internationale en ligne: levitra generique prix en pharmacie – pharmacie en ligne france livraison internationale

  8. EdwardGROOM表示:

    pharmacie en ligne pas cher: acheter kamagra site fiable – Pharmacie en ligne livraison Europe

  9. JseraldAposy表示:

    Не Отдают Диплом О Высшем Образовании
    Наша компания поможет вам недорого купить диплом в Подольске. Гарантируем строгую конфиденциальность, образованье и быстроту выполнения вашего заказа Купить диплом в Ангарске с нашей компанией быстро и просто. Для этого Вам нужно лишь выбрать то высшее учебное заведение, диплом которого Вы хотели бы получить. Наша компания работает без предоплаты Купить диплом о высшем образовании в Воронеже с нашей компанией можно очень быстро и просто. Для этого Вам нужно лишь выбрать и оформить заказ на нашем сайте. Фото – Диплома специалиста 2004-2008 года И это не шутка, сегодня вполне реально купить диплом в Краснодаре, Казани, Москве или в любом другом городе России.
    https://rudik-diploms-srednee.ru
    Мигуп Якутск
    Бакалавриат – ускоренная программа высшего образования, европейские магистратуры принимают российских бакалавров, основное отличие лежит в сфере применения знаний. Если вы решили заказать диплом магистра, оставьте заявку у нас на сайте или позвоните нашим консультантам. Все по-разному решают вопрос о том, где найти информацию для дипломной работы. Наша фирма продает документы, которые способны пройти любую проверку на подлинность.
    Диплом О Профессиональной Переподготовке Статус
    Срок обучения на программе магистратуры составляет, в среднем, от 2-х до 4-х лет. По общему мнению, проект позволит разоблачить тех, кто успел купить липовые дипломы о высшем образовании. Для членов семей заявителей необходимо также представить документы о степени родства: свидетельства о рождении или браке, документ о попечительстве или усыновлении.

  10. Allenacurf表示:

    pharmacie en ligne fiable: pharmacie en ligne france fiable – pharmacie en ligne fiable

  11. It’s appropriate time to make some plans for the long run and it is time to be happy. I have read this submit and if I may I desire to suggest you some fascinating things or advice. Perhaps you can write subsequent articles referring to this article. I desire to learn even more things approximately it!

  12. IgnacioSlima表示:

    pharmacie en ligne france livraison internationale: pharmacie en ligne sans ordonnance – vente de mГ©dicament en ligne

  13. Hiya, I’m really glad I’ve found this info. Today bloggers publish only about gossips and web and this is really annoying. A good site with exciting content, that’s what I need. Thanks for keeping this site, I will be visiting it. Do you do newsletters? Can not find it.

  14. whoah this blog is excellent i love reading your articles. Keep up the good work! You know, a lot of people are looking around for this info, you can aid them greatly.

  15. A few things i have observed in terms of laptop memory is that often there are specific features such as SDRAM, DDR etc, that must match up the features of the mother board. If the computer’s motherboard is reasonably current while there are no operating system issues, upgrading the storage space literally takes under 1 hour. It’s on the list of easiest laptop upgrade types of procedures one can visualize. Thanks for discussing your ideas.

  16. Jogos de azar no melhor cassino Fortune Tiger

  17. Tente a sua sorte neste cassino Fortune Tiger

  18. Allenacurf表示:

    pharmacie en ligne pas cher: pharmacie en ligne pas cher – acheter mГ©dicament en ligne sans ordonnance

  19. Allenacurf表示:

    vente de mГ©dicament en ligne: levitra generique prix en pharmacie – acheter mГ©dicament en ligne sans ordonnance

  20. IgnacioSlima表示:

    trouver un mГ©dicament en pharmacie: pharmacie en ligne pas cher – п»їpharmacie en ligne france

  21. EdwardGROOM表示:

    pharmacie en ligne livraison europe: pharmacie en ligne fiable – п»їpharmacie en ligne france

  22. Allenacurf表示:

    pharmacie en ligne fiable: pharmacie en ligne – Pharmacie en ligne livraison Europe

  23. IgnacioSlima表示:

    Achat mГ©dicament en ligne fiable: Levitra 20mg prix en pharmacie – pharmacie en ligne fiable

  24. Escolha este cassino confiavel Fortune Tiger

  25. Confie neste cassino confiavel Fortune Tiger

  26. XRumer23obliz表示:

    Hello.

    This post was created with XRumer 23 StrongAI.

    Good luck 🙂

  27. Allenacurf表示:

    pharmacie en ligne avec ordonnance: kamagra oral jelly – pharmacie en ligne france livraison internationale

  28. Cassinos com condicoes favoraveis Fortune Tiger

  29. Os melhores bonus deste cassino Fortune Tiger

  30. RobertBlica表示:

    https://viaenligne.com/# Acheter viagra en ligne livraison 24h

發佈留言

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