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

38,408 Responses

  1. DavidCooth表示:

    http://garuda888.top/# Slot dengan grafis 3D sangat mengesankan

  2. Williecrady表示:

    Banyak kasino memiliki program loyalitas untuk pemain https://garuda888.top/# Keseruan bermain slot selalu menggoda para pemain

  3. Williecrady表示:

    Kasino sering mengadakan turnamen slot menarik http://garuda888.top/# Pemain sering mencoba berbagai jenis slot

  4. Williecrady表示:

    Kasino di Indonesia menyediakan hiburan yang beragam http://bonaslot.site/# Banyak pemain mencari mesin dengan RTP tinggi

  5. Aaronbus表示:

    BonaSlot BonaSlot п»їKasino di Indonesia sangat populer di kalangan wisatawan

  6. DavidCooth表示:

    http://bonaslot.site/# Keseruan bermain slot selalu menggoda para pemain

  7. ThomasThype表示:

    Bermain slot bisa menjadi pengalaman sosial: bonaslot.site – bonaslot

  8. JamesLok表示:

    Slot menawarkan kesenangan yang mudah diakses https://preman69.tech/# Bermain slot bisa menjadi pengalaman sosial

  9. Tax Rebates: You need to ensure that your taxes are calculated properly and paid on time.

  10. Excellent blog right here! Additionally your website loads up fast! What web host are you the usage of? Can I get your associate hyperlink in your host? I wish my site loaded up as fast as yours lol

  11. DavidCooth表示:

    https://garuda888.top/# Permainan slot bisa dimainkan dengan berbagai taruhan

  12. Fox表示:

    Sweet blog! I found it while surfing around on Yahoo News. Do you have any tips on how to get listed in Yahoo News? I’ve been trying for a while but I never seem to get there! Appreciate it

  13. Williecrady表示:

    Slot dengan bonus putaran gratis sangat populer http://preman69.tech/# Mesin slot baru selalu menarik minat

  14. Its like you read my mind! You seem to know a lot about this, like you wrote the book in it or something. I think that you can do with a few pics to drive the message home a bit, but other than that, this is great blog. A great read. I will certainly be back.

  15. FoxBusiness表示:

    Throughout the grand design of things you actually get an A+ for effort and hard work. Exactly where you confused us ended up being in the details. You know, they say, the devil is in the details… And it couldn’t be more true right here. Having said that, permit me say to you just what exactly did do the job. Your writing can be incredibly convincing and that is most likely the reason why I am taking the effort to opine. I do not really make it a regular habit of doing that. Secondly, even though I can certainly notice a leaps in reasoning you make, I am not necessarily certain of exactly how you seem to connect your points which inturn help to make your conclusion. For right now I shall yield to your point but hope in the future you connect the facts better.

  16. ThomasThype表示:

    Banyak pemain menikmati bermain slot secara online: slot demo – slot demo rupiah

  17. Предлагаем услуги профессиональных инженеров офицальной мастерской.
    Еслли вы искали ремонт фотоаппаратов canon, можете посмотреть на сайте: ремонт фотоаппаратов canon цены
    Наши мастера оперативно устранят неисправности вашего устройства в сервисе или с выездом на дом!

  18. Proper now, the world of on-line buying is transforming with store-now-pay-later models.

  19. ThomasThype表示:

    Banyak pemain berusaha untuk mendapatkan jackpot: slot88 – slot88.company

  20. DavidCooth表示:

    https://bonaslot.site/# Jackpot besar bisa mengubah hidup seseorang

  21. Предлагаем услуги профессиональных инженеров офицальной мастерской.
    Еслли вы искали ремонт фотоаппаратов canon рядом, можете посмотреть на сайте: ремонт фотоаппаратов canon цены
    Наши мастера оперативно устранят неисправности вашего устройства в сервисе или с выездом на дом!

  22. ThomasThype表示:

    Kasino di Jakarta memiliki berbagai pilihan permainan: bonaslot.site – bonaslot

  23. Williecrady表示:

    Pemain harus menetapkan batas saat bermain https://garuda888.top/# Banyak kasino memiliki program loyalitas untuk pemain

  24. DavidCooth表示:

    https://slotdemo.auction/# Mesin slot menawarkan berbagai tema menarik

  25. Williecrady表示:

    Slot dengan grafis 3D sangat mengesankan http://preman69.tech/# Slot modern memiliki grafik yang mengesankan

  26. Financial disequilibrium concept has always been a part of the Austrian Financial principle.

  27. Круглосуточная доставка спиртного в Москве: комфорт либо проблема?

    Как это функционирует?

    24-часовая поставка алкоголя в Москве производится через различные сервисы:

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

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

    Законность: В РФ не разрешена продажа спиртного в ночное время (от 23:00 до 8:00). Сервисы доставки, которые предоставляют 24-часовую поставку, обычно применяют различные схемы, которые могут быть противозаконными. Употребление алкоголя: Простой получение к спиртному в любое время способен способствовать росту употребления, что способен повлечь отрицательные результаты для здоровья. Контроль за продажей не достигшим совершеннолетия: Существует опасность, что доставщики могут не контролировать лета клиентов, что способен вызвать к продаже алкоголя не достигшим совершеннолетия.

  28. I have taken notice that in digital camera models, unique sensors help to {focus|concentrate|maintain focus|target|a**** automatically. The particular sensors associated with some cameras change in contrast, while others start using a beam of infra-red (IR) light, especially in low lumination. Higher specification cameras often use a combination of both programs and probably have Face Priority AF where the video camera can ‘See’ any face while keeping your focus only in that. Many thanks for sharing your notions on this website.

  29. These days of austerity and also relative anxiety about incurring debt, many people balk about the idea of utilizing a credit card to make purchase of merchandise or even pay for any occasion, preferring, instead just to rely on this tried plus trusted approach to making repayment – hard cash. However, if you possess cash there to make the purchase 100 , then, paradoxically, that is the best time just to be able to use the credit card for several motives.

  30. JamesLok表示:

    Permainan slot bisa dimainkan dengan berbagai taruhan http://slotdemo.auction/# Slot menawarkan berbagai jenis permainan bonus

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

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