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

16,829 Responses

  1. Thus a human soul is the diyyuqna’ of the human monad.

  2. リネイヴ表示:

    Nevertheless, that’s not to say that Amal’s pals didn’t have issues about George’s ladies man status.

  3. RobertHam表示:

    https://erepharm.com/# ED meds online

  4. 僕の 英語表示:

    It’s a reasonably complicated sport, however despite the fact that you recognize the exercises that you are going to be doing – you’re always going to do these workout routines – there’s going to be a giant difference as far because the order of these exercises.

  5. Martini put together new witnesses for the city, including Reverend William Dunn of the St.

  6. Gdinrg表示:

    cost estrace 2mg – ginette 35 ca anastrozole sale

  7. Immerse the ornaments of Irani Feroza gemstone in the Gangajal, uncooked milk, & Tulsi leaves for cleansing and activation.

  8. Trams for transporting injured individuals waited for the lazaretto trains on the loading stations.

  9. 大東株価表示:

    Nice! Now it’s time to get down to making some good quaint arts & crafts.

  10. 24166373 Warrant Officer Class 2 James McCann Graham Wilson, Royal Corps of Transport.

  11. Peter Evelyn Leslie, Chairman, Export Guarantees Advisory Council, currently Deputy Chairman, Barclays Bank plc.

  12. A simple remedy will clear up that.- It’s dangerous for babies to be round dog food unsupervised.

  13. The Administration ‘appears ahead to working with the Congress to enact this legislation and be sure that it’s successfully implemented,’ it said.

  14. promotions表示:

    Would you be inquisitive about exchanging links?

  15. 8. Tread on serpents and scorpions (demonic angels and spirits).

  16. They mention they’re straightforward to clean, stains come out properly, and are great for drying their fingers.

  17. Скачайте додаток Mostbet і грайте будь-де | Легко і зручно – ставки на Mostbet | Зареєструйтеся на Mostbet та почніть грати прямо зараз | Скачайте додаток Mostbet та насолоджуйтеся швидким доступом до ігор | Отримайте доступ до ексклюзивних ігор на Mostbet мостбет скачать

  18. вывод из запоя ростов и область to.iboard.ws/viewtopic.php?id=8062#p17998 .

  19. вывод из запоя ростов на дону forumbar.anihub.me/viewtopic.php?id=9752 .

  20. анонимный. вывод. из. запоя. ростов. анонимный. вывод. из. запоя. ростов. .

  21. Gaul, Gilbert M. (2011-09-26).

  22. Some admire the value for money and quality of the product.

  23. вывод из запоя на дому ростов цены http://www.angelladydety.getbb.ru/viewtopic.php?f=44&t=42909 .

  24. Sea province measurement did not work for Bunch of random maps.

  25. Keep your child rising well by together with iron-rich foods of their weight loss program, like meat, seafood, beans, and spinach.鄔林樺 (2018-06-28).

  26. Making it fun helps engage those who would in any other case tune out the content material.

發佈留言

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