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

37,669 Responses

  1. BillieLet表示:

    kamagra oral jelly: Achetez vos kamagra medicaments – Kamagra Commander maintenant

  2. Howdy! This is my first visit to your blog! We are a group of volunteers and starting a new initiative in a community in the same niche. Your blog provided us valuable information to work on. You have done a marvellous job!

  3. Nice read, I just passed this onto a friend who was doing a little research on that. And he actually bought me lunch as I found it for him smile Therefore let me rephrase that: Thanks for lunch!

  4. Howdy! Do you know if they make any plugins to help with Search Engine Optimization? I’m trying to get my blog to rank for some targeted keywords but I’m not seeing very good success. If you know of any please share. Appreciate it!

  5. TerryDek表示:

    The voice of ‘White Lotus’ star Walton Goggins is the lullaby we didn’t know we needed
    jumper exchange
    While his “White Lotus” character Rick has been the source of some stress this season, Walton Goggins is here to soothe us into a state of dreamy sleep to make up for it.

    The actor has partnered with relaxation and meditation app Calm for one of their famed Sleep Stories, lending his smoky voice to a fable titled “The Yard Sale.”

    Goggins announced the Sleep Story on his verified Instagram on Tuesday, writing, “A friend once said to me the first question you ask someone shouldn’t be, ‘How are you?’ but rather, ‘How did you sleep last night?’ I agree.”

    The post included an excerpt from the story, in which Goggins is heard languidly instructing listeners to relax their bodies and get into bed. “You could even climb into a hammock,” he added. “I wouldn’t do that because I’ve never gracefully got in or out of one.”

    In the caption, the actor also wrote that he “wanted to create a Sleep Story that feels dreamlike, helping people slow their minds down by wandering through a yard sale (which happens to be one of my favorite things to do), uncovering hidden treasures.”

    “It’s the Walton Goggins version of counting sheep. I hope you enjoy,” he added.

    Other celebrities who have read bedtime stories in the hopes of putting audiences to sleep include Dolly Parton and the late Jimmy Stewart, whose voice was featured in a Calm Christmas Sleep Story in 2023 thanks to generative AI technology.

    Goggins currently stars on “The White Lotus,” where his character is often the most stressed out and tortured of the ensemble, at one point setting a slew of snakes free.

  6. Wonderful paintings! That is the type of information that should be shared across the internet. Disgrace on the seek engines for not positioning this post higher! Come on over and discuss with my site . Thanks =)

  7. WONDERFUL Post.thanks for share..more wait .. ?

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

  9. Hi! Quick question that’s completely off topic. Do you know how to make your site mobile friendly? My weblog looks weird when browsing from my iphone. I’m trying to find a template or plugin that might be able to resolve this problem. If you have any recommendations, please share. With thanks!

  10. Hmm is anyone else having problems with the pictures on this blog loading? I’m trying to determine if its a problem on my end or if it’s the blog. Any responses would be greatly appreciated.

  11. Peterclada表示:

    Cialis generique prix Cialis generique prix Tadalafil sans ordonnance en ligne tadalmed.com

  12. 牛樟芝肝表示:

    Its like you read my mind! You appear to know a lot about this, like you wrote the book in it or something. I think that you could do with some pics to drive the message home a little bit, but instead of that, this is wonderful blog. A fantastic read. I’ll certainly be back.

  13. BradleyJaire表示:

    Acheter Cialis: Achat Cialis en ligne fiable – cialis generique tadalmed.shop

  14. BillieLet表示:

    Acheter Kamagra site fiable: Achetez vos kamagra medicaments – kamagra gel

  15. Thanks for these tips. One thing I additionally believe is the fact that credit cards featuring a 0 rate of interest often appeal to consumers along with zero monthly interest, instant acceptance and easy on-line balance transfers, nevertheless beware of the top factor that can void your current 0 easy neighborhood annual percentage rate and also throw one out into the poor house fast.

  16. Whats up this is kinda of off topic but I was wanting to know if blogs use WYSIWYG editors or if you have to manually code with HTML. I’m starting a blog soon but have no coding knowledge so I wanted to get advice from someone with experience. Any help would be greatly appreciated!

  17. Bernardshoor表示:

    Tadalafil sans ordonnance en ligne: Tadalafil 20 mg prix sans ordonnance – Pharmacie en ligne Cialis sans ordonnance tadalmed.shop

  18. Bernardshoor表示:

    pharmacie en ligne fiable: Pharmacies en ligne certifiees – pharmacie en ligne france livraison internationale pharmafst.com

  19. 白牛樟芝表示:

    Thanks for enabling me to achieve new tips about personal computers. I also contain the belief that certain of the best ways to help keep your notebook in leading condition is with a hard plastic material case, or maybe shell, that fits over the top of the computer. Most of these protective gear are usually model specific since they are manufactured to fit perfectly above the natural outer shell. You can buy these directly from the vendor, or from third party places if they are readily available for your laptop computer, however not every laptop may have a spend on the market. Once more, thanks for your tips.

  20. you may have a terrific weblog here! would you wish to make some invite posts on my blog?

  21. Bernardshoor表示:

    kamagra livraison 24h: kamagra livraison 24h – Achetez vos kamagra medicaments

  22. BradleyJaire表示:

    Cialis en ligne: cialis generique – Cialis en ligne tadalmed.shop

  23. Thanks for the strategies you are revealing on this web site. Another thing I’d really like to say is that getting hold of copies of your credit rating in order to scrutinize accuracy of each and every detail may be the first activity you have to execute in credit improvement. You are looking to freshen your credit profile from dangerous details flaws that spoil your credit score.

  24. Электроприводные деревянные жалюзи: комфорт и стиль
    Деревянные горизонтальные жалюзи с электроприводом Деревянные горизонтальные жалюзи с электроприводом . прокарниз

  25. MarceloJed表示:

    смотреть русские фильмы фильмы в 4К бесплатно онлайн

  26. PatrickPlept表示:

    фильм драма с высоким рейтингом фильмы в 4К бесплатно онлайн

  27. Robertfap表示:

    https://pharmafst.shop/# pharmacie en ligne france pas cher

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

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