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,677 Responses

  1. Excelente cassino para ganhos Blaze

  2. WilliamTic表示:

    Сегодня, когда аттестат становится началом удачной карьеры в любой области, многие пытаются найти максимально быстрый и простой путь получения качественного образования. Наличие официального документа об образовании переоценить невозможно. Ведь диплом открывает двери перед всеми, кто стремится вступить в сообщество профессионалов или учиться в университете.
    В данном контексте наша компания предлагает очень быстро получить этот важный документ. Вы имеете возможность заказать аттестат, и это становится удачным решением для всех, кто не смог завершить образование или потерял документ. Каждый аттестат изготавливается с особой аккуратностью, вниманием к мельчайшим нюансам, чтобы на выходе получился документ, 100% соответствующий оригиналу.
    Превосходство данного подхода заключается не только в том, что вы сможете оперативно получить свой аттестат. Процесс организован комфортно, с профессиональной поддержкой. От выбора подходящего образца аттестата до точного заполнения личной информации и доставки в любой регион страны — все находится под полным контролем квалифицированных мастеров.
    Для всех, кто пытается найти быстрый и простой способ получить необходимый документ, наша компания может предложить выгодное решение. Заказать аттестат – это значит избежать длительного процесса обучения и не теряя времени переходить к своим целям: к поступлению в университет или к началу успешной карьеры.

    http://uralhistory.ru/galereya_2/foto_1910_goda_fotograf_sm_prokudinagorskogo_2

  3. O melhor cassino on-line para voce Blaze

  4. O lugar perfeito para jogos de azar Blaze

  5. Отличный сайт! Всем рекомендую!охотничий магазин

  6. гейтс оф олимпус играть гейтс оф олимпус играть .

  7. Eu recomendo o melhor cassino Blaze

  8. O melhor cassino para jogadores de verdade Blaze

  9. Отличный сайт! Всем рекомендую!магазин товаров для охоты

  10. Diplomi_ubki表示:

    купить диплом юриста russa24-diploms-srednee.com .

  11. Teste sua sorte no melhor cassino Blaze

  12. Tente sua sorte nos melhores cassinos Blaze

  13. Lcvogr表示:

    order enalapril 5mg for sale – order generic doxazosin 1mg where to buy xalatan without a prescription

  14. Experimente o cassino mais popular Blaze

  15. Top Stage Hypnotist for hire Kristian von Sponneck performs private stage hypnosis shows anywhere in the UK, Europe or worldwide. Hire hime for your next event!

  16. Top Stage Hypnotist for hire Kristian von Sponneck performs private stage hypnosis shows anywhere in the UK, Europe or worldwide. Hire hime for your next event!

  17. Top Stage Hypnotist for hire Kristian von Sponneck performs private stage hypnosis shows anywhere in the UK, Europe or worldwide. Hire hime for your next event!

  18. Seu cassino online favorito Blaze

  19. Sua sorte esta no cassino confiavel Blaze

  20. Top Stage Hypnotist for hire Kristian von Sponneck performs private stage hypnosis shows anywhere in the UK, Europe or worldwide. Hire hime for your next event!

  21. Hello, you used to write excellent, but the last several posts have been kinda boring? I miss your tremendous writings. Past several posts are just a little bit out of track! come on!

  22. Thanks for revealing your ideas. I would also like to mention that video games have been ever before evolving. Today’s technology and revolutions have served create sensible and fun games. All these entertainment video games were not that sensible when the real concept was first being used. Just like other areas of technological innovation, video games as well have had to evolve through many generations. This itself is testimony towards fast growth and development of video games.

  23. Dmykkt表示:

    dramamine 50mg cheap – prasugrel 10mg canada purchase actonel sale

  24. FobertWen表示:

    Thanks a bunch for sharing this with all of us you actually recognise what you are speaking about! Bookmarked. Kindly also discuss with my website =). We can have a link change agreement between us
    arusak-attestats24.com

    This is very interesting, You’re an overly skilled blogger. I’ve joined your feed and look ahead to seeking extra of your magnificent post. Additionally, I’ve shared your web site in my social networks

  25. O cassino mais popular Blaze

  26. Another thing I have really noticed is for many people, less-than-perfect credit is the reaction of circumstances over and above their control. For example they may be really saddled through an illness so they have substantial bills going to collections. It might be due to a occupation loss and the inability to work. Sometimes divorce proceedings can send the finances in the wrong direction. Many thanks for sharing your opinions on this website.

  27. O melhor cassino para grandes vitorias Blaze

  28. Shaneevige表示:

    Keep this going please, great job!

    2xaynha.com/2014/09/18В 
    familylevel.com/blogs/19/Why-is-the-demand-and-popularity-of-universities-decreasing-todayВ 
    gamemotors.ru/page/11В 
    http://www.autopasjonaci.pl/forum/viewtopic.php?f=24&t=247250В 
    conservatives.click/index.php?do=/public/user/blogs/name_Alanpoe/page_7/В 

  29. Thanks for your post. I also feel that laptop computers are becoming more and more popular currently, and now are sometimes the only kind of computer found in a household. It is because at the same time they are becoming more and more economical, their computing power is growing to the point where they are as potent as personal computers through just a few years ago.

發佈留言

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