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

15,640 Responses

  1. zentai表示:

    Thanks for the points you have shared here. Another thing I would like to express is that personal computer memory demands generally go up along with other advances in the know-how. For instance, any time new generations of processor chips are made in the market, there is usually a matching increase in the size and style calls for of all personal computer memory and hard drive room. This is because software program operated by means of these cpus will inevitably boost in power to leverage the new technological innovation.

  2. Vgsqoq表示:

    buy artane sale – artane pills order voltaren gel sale

  3. One thing I’d prefer to say is that often before obtaining more personal computer memory, have a look at the machine in which it will be installed. In case the machine is actually running Windows XP, for instance, a memory threshold is 3.25GB. Setting up a lot more than this would simply constitute a new waste. Be sure that one’s mother board can handle the actual upgrade volume, as well. Good blog post.

  4. zentai表示:

    What an eye-opening and thoroughly-researched article! The author’s meticulousness and capability to present complicated ideas in a comprehensible manner is truly commendable. I’m extremely captivated by the depth of knowledge showcased in this piece. Thank you, author, for offering your expertise with us. This article has been a real game-changer!

  5. Richardral表示:

    farmacie online affidabili Cialis generico farmacia farmacie online affidabili

  6. I think this is among the most vital information for me. And i’m glad reading your article. But should remark on few general things, The web site style is great, the articles is really nice : D. Good job, cheers

  7. It?s actually a cool and useful piece of information. I am glad that you simply shared this helpful info with us. Please stay us up to date like this. Thanks for sharing.

  8. zentai表示:

    An additional issue is that video games are usually serious naturally with the major focus on knowing things rather than entertainment. Although, we have an entertainment factor to keep your children engaged, every game is often designed to work with a specific group of skills or program, such as numbers or science. Thanks for your write-up.

  9. Richardral表示:

    Farmacia online piГ№ conveniente Ibuprofene 600 prezzo senza ricetta Farmacie on line spedizione gratuita

  10. Сервисный центр предлагает починка мониторов aoc центр ремонта монитора aoc

  11. I have seen that car insurance firms know the cars and trucks which are prone to accidents and various risks. Additionally, these people know what types of cars are given to higher risk and also the higher risk they have got the higher your premium amount. Understanding the uncomplicated basics connected with car insurance will let you choose the right sort of insurance policy that will take care of your preferences in case you happen to be involved in any accident. Thank you sharing a ideas in your blog.

  12. MichaelToP表示:

    Farmacie on line spedizione gratuita Cialis generico 20 mg 8 compresse prezzo acquistare farmaci senza ricetta

  13. Kennethtub表示:

    http://sildenafilit.pro/# cialis farmacia senza ricetta
    comprare farmaci online all’estero

  14. Kennethtub表示:

    http://brufen.pro/# Brufen 600 senza ricetta
    п»їFarmacia online migliore

  15. MichaelToP表示:

    migliori farmacie online 2024 Cialis generico 5 mg prezzo Farmacie online sicure

  16. Kennethtub表示:

    http://sildenafilit.pro/# viagra 100 mg prezzo in farmacia
    comprare farmaci online all’estero

  17. MichaelToP表示:

    farmacie online affidabili Farmacie online sicure farmacia online piГ№ conveniente

  18. Edgarappow表示:

    farmacia senza ricetta recensioni: viagra online siti sicuri – siti sicuri per comprare viagra online

  19. Edgarappow表示:

    farmacie online affidabili: Brufen 600 senza ricetta – farmacia online senza ricetta

  20. Edgarappow表示:

    acquisto farmaci con ricetta: Farmacia online migliore – migliori farmacie online 2024

  21. Richardral表示:

    Farmacie online sicure BRUFEN 600 bustine prezzo п»їFarmacia online migliore

  22. PatrickLef表示:

    comprare farmaci online all’estero: Brufen antinfiammatorio – top farmacia online

  23. Richardral表示:

    comprare farmaci online all’estero Farmacie online sicure Farmacia online miglior prezzo

  24. Richardral表示:

    п»їFarmacia online migliore farmacia online migliore Farmacie online sicure

  25. MichaelToP表示:

    farmacia online piГ№ conveniente Farmacie online sicure farmacia online piГ№ conveniente

  26. Chernyy_ivSa表示:

    Советы по выбору черного плинтуса для дома, За и против черного плинтуса в интерьере, Топ-10 дизайнерских идей с черным плинтусом, Как правильно ухаживать за черным плинтусом, Советы по подбору черного плинтуса для дома, Зачем выбирать черный плинтус для интерьера, Современные тренды в использовании черного плинтуса, Какие фактуры черного плинтуса пользуются популярностью, Черный плинтус в классическом интерьере: удачное сочетание, Роль черного плинтуса в оформлении интерьера, Почему черный плинтус становится все популярнее, Черный плинтус в королевском стиле: особенности декорирования, Черный плинтус: отличие от других видов плинтусов, Черный плинтус на стенах: стройность и элегантность, Идеи использования черного плинтуса на кухне, Чем привлекательны черные оттенки в спальном интерьере, Идеи использования черного плинтуса в гостиной, Черный плинтус: шикарный акцент в ванной комнате, Как черный плинтус может изменить ваше пространство
    плинтус алюминиевый черный плинтус алюминиевый черный .

  27. replica shoes tv938
    Replica Sneakers for Men,Replica Sneakers for
    women nr545

  28. Если вы искали где отремонтировать сломаную технику, обратите внимание – ремонт бытовой техники в воронеже

發佈留言

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