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

9,705 Responses

  1. Thanks for revealing your ideas. I might also like to express that video games have been actually evolving. Modern technology and improvements have aided create sensible and interactive games. All these entertainment games were not actually sensible when the real concept was first of all being experimented with. Just like other designs of technological innovation, video games way too have had to grow via many ages. This itself is testimony for the fast development of video games.

  2. I?m impressed, I have to say. Actually hardly ever do I encounter a blog that?s each educative and entertaining, and let me tell you, you’ve gotten hit the nail on the head. Your thought is excellent; the difficulty is one thing that not enough individuals are speaking intelligently about. I’m very comfortable that I stumbled throughout this in my search for one thing relating to this.

  3. Pcwhfw表示:

    buy speman tablets – fincar order buy cheap fincar

  4. Nice post. I was checking continuously this weblog and I’m impressed! Very helpful information particularly the remaining phase 🙂 I care for such information a lot. I was looking for this particular info for a long time. Thanks and good luck.

  5. Some tips i have continually told people is that while looking for a good internet electronics retail store, there are a few factors that you have to take into consideration. First and foremost, you should make sure to get a reputable along with reliable shop that has got great assessments and classification from other consumers and business sector analysts. This will make certain you are getting through with a well-known store that gives good services and support to the patrons. Many thanks sharing your opinions on this blog site.

  6. Hi there! Do you know if they make any plugins to help with SEO? I’m trying to get my blog to rank for some targeted keywords but I’m not seeing very good results. If you know of any please share. Appreciate it!

  7. Hi there! I know this is kinda 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 options for another platform. I would be fantastic if you could point me in the direction of a good platform.

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

  9. Используйте 1win зеркало для доступа к сайту даже при блокировке.

  10. Ищете надёжный ресурс? 1вин сайт предоставляет всё необходимое для азартных игр.

  11. 1вин казино предлагает уникальные бонусы и высокие шансы на выигрыш.

  12. 1win официальный сайт гарантирует честные игры и надежные выплаты.

  13. Попробуйте свою удачу в 1win casino и выиграйте крупные призы.

  14. Dnrtmzx表示:

    Привет, друзья!
    Купить документ университета вы сможете у нас в Москве.
    ast-diploms24.ru/kupit-diplom-o-srednem-obrazovanii
    Хорошей учебы!

  15. Играть в 1win казино можно с любым устройством, получая удовольствие от высокого качества игр.

  16. На 1вин сайт вы найдете последние новости и лучшие предложения для игроков.

  17. Официальный 1win сайт предлагает разнообразные азартные игры и выгодные ставки.

  18. 1вин официальный сайт предоставляет удобный интерфейс и множество бонусов для новых пользователей.

  19. Посетите 1win официальный сайт для получения доступа к широкому ассортименту игр и ставок.

  20. Diplomi_hxEa表示:

    Привет!
    Заказать документ о получении высшего образования можно у нас.
    diplomyx.com/kupit-diplom-krasnodar 

  21. лучшие капперы в телеграмме лучшие капперы в телеграмме .

  22. Lazrfln表示:

    Привет!
    Купить диплом любого университета.
    k96586v0.beget.tech/component/comprofiler/pluginclass/cbblogs.html?action=blogs&func=show&id=140

  23. Mazrhqs表示:

    Привет!
    Как официально купить диплом вуза с упрощенным обучением в Москве
    worldgonews.ru/diplomyi-ot-luchshih-vuzov

  24. JamesBak表示:

    cipro online no prescription in the usa: buy cipro – cipro

  25. Идеальное место для азартных игр 1вин

  26. Рекомендую лучшего букмекера 1win

  27. JamesBak表示:

    п»їpaxlovid: paxlovid pill – paxlovid pill

  28. Отличный сайт! Всем рекомендую!типография

  29. Eanrqpf表示:

    Привет!
    Мы предлагаем дипломы любой профессии по приятным ценам.
    forum.rucarp.ru/album.php?albumid=128&attachmentid=35736&commentid=1960
    Поможем вам всегда!

  30. Cazrals表示:

    Добрый день!
    Мы предлагаем документы техникумов, расположенных в любом регионе России. Можно купить качественно напечатанный диплом за любой год, указав актуальную специальность и хорошие оценки за все дисциплины. Документы выпускаются на бумаге высшего качества. Это позволяет делать настоящие дипломы, не отличимые от оригиналов. Документы заверяются всеми обязательными печатями и подписями.
    cubarebota.info/blogs/166/%D0%9A%D0%B0%D0%BA-%D0%BC%D0%BE%D0%B6%D0%BD%D0%BE-%D0%BD%D0%B5%D0%B4%D0%BE%D1%80%D0%BE%D0%B3%D0%BE-%D0%BF%D1%80%D0%B8%D0%BE%D0%B1%D1%80%D0%B5%D1%81%D1%82%D0%B8-%D0%B0%D1%82%D1%82%D0%B5%D1%81%D1%82%D0%B0%D1%82-%D0%B2-%D0%B8%D0%BD%D1%82%D0%B5%D1%80%D0%BD%D0%B5%D1%82-%D0%BC%D0%B0%D0%B3%D0%B0%D0%B7%D0%B8%D0%BD%D0%B5

發佈留言

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