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

27,850 Responses

  1. WilsonVah表示:

    Pharmacie Internationale en ligne: pharmacie en ligne pas cher – pharmacie en ligne fiable

  2. Non-public (various) loans are by means of banks and other lending institutions and operate a lot the same as other consumer loans: the phrases differ, typically significantly, from lender to lender.

  3. Richardprurf表示:

    http://tadalafilmeilleurprix.com/# Pharmacie en ligne livraison Europe
    pharmacie en ligne france pas cher

  4. NorbertKep表示:

    pharmacie en ligne pas cher: pharmacie en ligne pas cher – pharmacies en ligne certifiГ©es

  5. Richardprurf表示:

    http://viagrameilleurprix.com/# SildГ©nafil 100 mg sans ordonnance
    Pharmacie Internationale en ligne

  6. Richardprurf表示:

    http://pharmaciemeilleurprix.com/# trouver un mГ©dicament en pharmacie
    pharmacies en ligne certifiГ©es

  7. I’m in awe of the author’s ability to make complicated concepts approachable to readers of all backgrounds. This article is a testament to her expertise and commitment to providing valuable insights. Thank you, author, for creating such an captivating and illuminating piece. It has been an absolute pleasure to read!

  8. Perryzoozy表示:

    vente de mГ©dicament en ligne cialis generique vente de mГ©dicament en ligne

  9. NorbertKep表示:

    pharmacie en ligne avec ordonnance: achat kamagra – pharmacie en ligne france pas cher

  10. Jacobbep表示:

    pharmacie en ligne sans ordonnance https://viagrameilleurprix.com/# Viagra vente libre pays

  11. MicahNaw表示:

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

    1. Mega Moolah
    Знаменитый слот с растущим кушем, который уже сделал миллионерами много участников. Средний величина джекпота – несколько миллионов деревянных.

    2. Dead or Alive 2
    Непостоянный игровой автомат со уникальной механикой увеличения. Здесь можно выиграть до 100 000x с пари!

    3. Bonanza
    Игровой автомат с механикой Megaways, где количество выигрышных полос доходит 117 649. Хорош для тех людей, кому нравится активность и постоянные вознаграждения.

    4. Reactoonz
    Специфичный игровой автомат со кластерными выплатами. Тут нет обычных полос – призы делаются кучами значков.

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

    Совет из Vodka Casino:
    — До игрой смотрите RTP и переменчивость слота.
    — Применяйте бонусы и бесплатные вращения ради испытания новых игровых автоматов.

    Попробуйте данные слоты на интернет-сайте https://theseasons.ru/rus/pages/?kachestvennye_holodilynye_shkafy_pochemu_ih_stoit_imety_v_svoem_pomeschenii.html — и, возможно, следующий большой выигрыш станет вашим!

  12. Jacobbep表示:

    acheter mГ©dicament en ligne sans ordonnance http://tadalafilmeilleurprix.com/# pharmacie en ligne france pas cher

  13. WilsonVah表示:

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

  14. WilsonVah表示:

    pharmacie en ligne avec ordonnance: pharmacie en ligne sans ordonnance – pharmacie en ligne france livraison belgique

  15. WilsonVah表示:

    trouver un mГ©dicament en pharmacie: Acheter Cialis – pharmacie en ligne france fiable

  16. NorbertKep表示:

    pharmacie en ligne france livraison internationale: achat kamagra – Pharmacie sans ordonnance

  17. The board is supported by more than 60 staff.

  18. Perryzoozy表示:

    pharmacie en ligne fiable pharmacie en ligne france Achat mГ©dicament en ligne fiable

  19. With crowd evaluation, abnormal crowd patterns and behaviors may be detected, enabling prompt intervention to maintain crowd safety.

  20. MjhgdfxewKat表示:

    бесплатно эро чат
    русский эро чат эро чат бонга

  21. Perryzoozy表示:

    trouver un mГ©dicament en pharmacie Tadalafil sans ordonnance en ligne pharmacie en ligne france fiable

  22. Richardprurf表示:

    https://pharmaciemeilleurprix.shop/# pharmacie en ligne pas cher
    pharmacie en ligne livraison europe

  23. Good day! I know this is somewhat off topic but I was wondering which blog platform are you using for this site? I’m getting tired of WordPress because I’ve had issues with hackers and I’m looking at options for another platform. I would be awesome if you could point me in the direction of a good platform.

  24. эро видео чат пары
    эро пары чат бесплатный секс чат пары

  25. Good blog! I really love how it is simple on my eyes and the data are well written. I am wondering how I might be notified when a new post has been made. I have subscribed to your RSS which must do the trick! Have a great day!

  26. Roberttic表示:

    http://amohealthpharm.com/# amoxicillin 500mg price canada

  27. Roberttic表示:

    https://amohealthpharm.com/# where to get amoxicillin over the counter

發佈留言

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