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

34,947 Responses

  1. Curtismence表示:

    https://k8viet.guru/# k8 bet

  2. I’m really impressed along with your writing skills as neatly as with the format on your weblog. Is this a paid subject or did you modify it your self? Either way keep up the nice high quality writing, it is uncommon to see a great blog like this one these days..

  3. Wow, amazing blog structure! How lengthy have you ever been blogging for? you made blogging glance easy. The full look of your web site is excellent, as well as the content material!

  4. Wow, marvelous weblog structure! How lengthy have you ever been blogging for? you made running a blog look easy. The entire look of your web site is wonderful, let alone the content!

  5. Williamabesy表示:

    интернет магазин аккаунтов маркетплейс готовых аккаунтов

  6. Kevindal表示:

    покупка продажа аккаунтов где можно продать аккаунт

  7. RobertLoume表示:

    маркетплейсы для покупки аккаунта продажа аккаунтов онлайн

  8. Thanks for the guidelines you have provided here. Another thing I would like to state is that laptop or computer memory demands generally go up along with other breakthroughs in the technology. For instance, any time new generations of cpus are brought to the market, there’s usually a related increase in the dimensions calls for of all computer system memory and also hard drive room. This is because the software program operated by means of these cpus will inevitably boost in power to make new technological innovation.

  9. Spot on with this write-up, I truly suppose this web site needs much more consideration. I?ll most likely be once more to read far more, thanks for that info.

  10. You really make it appear so easy along with your presentation but I to find this matter to be actually something that I feel I would never understand. It seems too complicated and extremely wide for me. I am looking ahead in your subsequent publish, I?ll try to get the hang of it!

  11. Stevenkated表示:

    https://88betviet.pro/# nha cai 88bet

  12. Thanks a lot for the helpful article. It is also my belief that mesothelioma cancer has an extremely long latency interval, which means that indication of the disease may not emerge right until 30 to 50 years after the initial exposure to mesothelioma. Pleural mesothelioma, which is the most common form and influences the area around the lungs, might result in shortness of breath, upper body pains, including a persistent cough, which may bring on coughing up maintain.

  13. Josephsip表示:

    188bet 88bet: keo nha cai 88bet – 88 bet

  14. Curtismence表示:

    http://k8viet.guru/# k8 bet

  15. 1win_umer表示:

    1win партнёрка 1win827.ru .

  16. I know this if off topic but I’m looking into starting my own blog and was curious what all is required to get setup? I’m assuming having a blog like yours would cost a pretty penny? I’m not very internet savvy so I’m not 100 certain. Any tips or advice would be greatly appreciated. Thanks

  17. KevinbeR表示:

    Устал терять в игровом клубе? Хватит ставить вслепую! Присоединяйся на Канал “Рейтинг Казино”! ??

    Забудь о потерянных средствах и разочарованиях! Наш Telegram-канал “Наш канал” будет твоим лучшим помощником в мире гемблинга!

    Что же тебя ждет в здесь:

    Независимые анализы казино: Мы изучаем все – от лицензии и известности до плюшек и скорости переводов. Совершенно никаких пиара, лишь честная информация!
    Последние табели о рангах: Посмотри, какие именно казино действительно переводят деньги и обеспечивают самые выгодные условия для клиентов!
    Эксклюзивные подарки и промокоды: Бери наиболее прибыльные акции от проверенных платформ!
    Актуальные новости из мира ставок: Пребывай в теме свежих фактов и тенденций!
    Советы и тактики от бывалых пользователей: Увеличь свои возможности на выигрыш и ставь с головой!

    Довольно рассчитывать на фортуну! Пора играть обдуманно!

    Вступай на “Наш Telegram канал “Рейтинг Казино”” прямо сейчас и преобразуй игру в выгоду!

    https://telegra.ph/Sravnenie-Kazino-Rejting-po-Klyuchevym-Parametram-03-23-6

  18. Josephsip表示:

    link vao k8: k8vip – k8 bet

  19. I really like your wp template, wherever did you obtain it from?

  20. Hey very nice blog!! Man .. Excellent .. Amazing .. I’ll bookmark your blog and take the feeds also?I’m happy to find so many useful info here in the post, we need work out more techniques in this regard, thanks for sharing. . . . . .

  21. Josephsip表示:

    dang nh?p alo789: alo789 dang nh?p – 789alo

  22. 長崎 野球表示:

    In 1779, Fort Nashborough was constructed right here in 1779 by pioneers from North Carolina.

  23. Spot on with this write-up, I really assume this web site needs rather more consideration. I?ll in all probability be once more to learn far more, thanks for that info.

  24. Josephsip表示:

    alo789 dang nh?p: 789alo – alo789 chinh th?c

  25. Curtismence表示:

    http://alo789.auction/# alo789hk

  26. Rubengax表示:

    alo789 dang nh?p alo789 chinh th?c alo789 chinh th?c

發佈回覆給「1win_umer」的留言 取消回覆

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