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

  1. Jamesfeame表示:

    starzbet starzbet giris starzbet

  2. Jamesfeame表示:

    starzbet guvenilir mi starzbet giris starzbet guncel giris

  3. GeorgeAmarp表示:

    https://gatesofolympusoyna.online/# gates of olympus slot

  4. Jamesfeame表示:

    gates of olympus oyna gate of olympus oyna Gates of Olympus

  5. Хочу поделиться опытом покупки в одном интернет-магазине сантехники. Решил обновить ванную комнату и искал место, где можно найти широкий выбор раковин и ванн. Этот магазин приятно удивил своим ассортиментом и сервисом. Там есть всё: от классических чугунных ванн до современных акриловых моделей.

    Если вам нужна купить раковину , то это точно туда. Цены конкурентные, а качество товаров подтверждено сертификатами. Консультанты помогли с выбором, ответили на все вопросы. Доставка пришла вовремя, и установка прошла без проблем. Остался очень доволен покупкой и сервисом.

  6. Профессиональный сервисный центр по ремонту фототехники в Москве.
    Мы предлагаем: купить в москве фотовспышку дешево
    Наши мастера оперативно устранят неисправности вашего устройства в сервисе или с выездом на дом!
    Подробнее на сайте сервисного центра remont-vspyshek-realm.ru

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

  8. Профессиональный сервисный центр по ремонту компьютероной техники в Москве.
    Мы предлагаем: ремонт системного блока компьютера
    Наши мастера оперативно устранят неисправности вашего устройства в сервисе или с выездом на дом!

  9. Jamesfeame表示:

    betine guncel betine promosyon kodu 2024 betine guncel

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

  11. Jamesfeame表示:

    betine betine com guncel giris betine

  12. Jamesfeame表示:

    gates of olympus demo turkce oyna gates of olympus slot gate of olympus oyna

  13. Dino Game 232表示:

    whoah this weblog is fantastic i really like studying your posts. Keep up the good paintings! You realize, many people are looking round for this info, you can aid them greatly.

  14. Профессиональный сервисный центр по ремонту фототехники в Москве.
    Мы предлагаем: накамерная вспышка ремонт
    Наши мастера оперативно устранят неисправности вашего устройства в сервисе или с выездом на дом!
    Подробнее на сайте сервисного центра remont-vspyshek-realm.ru

  15. Dino Game 239表示:

    Many thanks for your post. I’d really like to comment that the cost of car insurance differs a lot from one insurance policy to another, due to the fact there are so many different facets which give rise to the overall cost. Such as, the make and model of the motor vehicle will have an enormous bearing on the fee. A reliable ancient family vehicle will have a more economical premium when compared to a flashy racecar.

  16. Dino Game 238表示:

    I have learned new things through your blog post. Also a thing to I have recognized is that generally, FSBO sellers may reject people. Remember, they might prefer to never use your providers. But if you maintain a comfortable, professional partnership, offering assistance and being in contact for around four to five weeks, you will usually manage to win interviews. From there, a listing follows. Thank you

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

  18. Casibomvow表示:

    casibom 158 giris: casibom guncel giris – casibom giris
    casibom giris

  19. Dino Game 232表示:

    Thanks for sharing superb informations. Your web site is so cool. I’m impressed by the details that you?ve on this web site. It reveals how nicely you understand this subject. Bookmarked this website page, will come back for extra articles. You, my friend, ROCK! I found just the info I already searched everywhere and just could not come across. What an ideal site.

  20. Dino Game 233表示:

    What?s Happening i’m new to this, I stumbled upon this I’ve found It absolutely helpful and it has helped me out loads. I hope to contribute & help other users like its aided me. Great job.

  21. Dino Game 232表示:

    An attention-grabbing dialogue is worth comment. I feel that you must write more on this topic, it won’t be a taboo subject but generally persons are not enough to talk on such topics. To the next. Cheers

  22. Casibomvow表示:

    casibom guncel giris: casibom giris adresi – casibom 158 giris
    casibom guncel giris adresi

  23. Casibomvow表示:

    casibom guncel giris adresi: casibom giris adresi – casibom guncel
    casibom guncel giris

  24. Casibomvow表示:

    casibom guncel giris adresi: casibom giris adresi – casibom guncel giris
    casibom giris

  25. Casibomvow表示:

    casibom giris adresi: casibom 158 giris – casibom guncel
    casibom guncel giris adresi

  26. Dino Game 235表示:

    you will have a terrific blog right here! would you like to make some invite posts on my weblog?

  27. Casibomvow表示:

    casibom: casibom – casibom giris
    casibom giris

  28. tegulkead表示:

    As well as real money casinos and slots, we also look at the best free games offered by big names such as Slotomania, LuckyLand Slots and Chumba Casino. These casinos all offer a fantastic selection of slot games, and what’s even better, you can get started playing for FREE! The great thing about slot games is that there’s just so many of them. The only downside? Getting started can be overwhelming. Which is why we’ve got your back with this online slots guide –– to help beginners navigate the sea of slot machines. Here at Ignition Casino, we’ve got the best online slot machines for real money and a weekly boost bonus to help you stretch out your bankroll. For even more free cash, tell a friend about us; we’ll give you up to $125. Offering multiple ways to access the best slot games online ensures more options for gamers. With the ability to connect via Facebook, Google or your email, you can enjoy the best slots on any device while saving your progress at the same time.
    https://idealpropertycentre.co.uk/casino-for-18yearolds-near-me
    Penny slots are named due to their minimum bet of a single cent per line. However, there’s a massive mistake a lot of players make – and that’s assuming that penny slots mean you only spend one penny each time you spin the game. This couldn’t be further from the truth, and while you can find penny slot machines that can be played from just one cent, most of the time, this is no longer the case today. I’d recommend that if you cannot afford to play the max coins in a slot machine, pick a lower denomination so that you can play the max coins (or play a two coin machine instead of a three coin machine, etc.) A platform created to showcase all of our efforts aimed at bringing the vision of a safer and more transparent online gambling industry to reality. You can still pay penny slots today both online and at the casino, for free or real money – but the name doesn’t truly reflect the reality.

  29. Dino Game 240表示:

    Thanks for your posting on the traveling industry. I might also like contribute that if your senior thinking of traveling, it truly is absolutely vital that you buy travel cover for senior citizens. When traveling, elderly people are at high risk of getting a health emergency. Getting the right insurance policies package on your age group can protect your health and provide you with peace of mind.

發佈留言

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