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

10,429 Responses

  1. Nice blog here! Also your site loads up fast! What web host are you using? Can I get your affiliate link to your host? I wish my site loaded up as fast as yours lol

  2. Thanks for the suggestions shared on the blog. Yet another thing I would like to mention is that weight-loss is not information on going on a dietary fad and trying to shed as much weight as you’re able in a couple of weeks. The most effective way to lose weight is by consuming it bit by bit and obeying some basic ideas which can help you to make the most through your attempt to drop some weight. You may learn and be following some of these tips, nonetheless reinforcing understanding never does any damage.

  3. I just like the valuable info you supply in your articles. I will bookmark your blog and check again here frequently. I am somewhat certain I will be informed plenty of new stuff proper here! Best of luck for the next!

  4. At this time it sounds like Drupal is the best blogging platform available right now. (from what I’ve read) Is that what you are using on your blog?

  5. hi!,I love your writing so a lot! proportion we keep in touch more about your post on AOL? I require a specialist on this area to unravel my problem. May be that’s you! Looking ahead to peer you.

  6. Hi there! I simply would like to give an enormous thumbs up for the great info you will have right here on this post. I might be coming back to your blog for more soon.

  7. I was recommended this website by my cousin. I am not sure whether this post is written by him as no one else know such detailed about my difficulty. You are wonderful! Thanks!

  8. Just wish to say your article is as amazing. The clarity in your post is just nice and i can assume you’re an expert on this subject. Fine with your permission let me to grab your RSS feed to keep updated with forthcoming post. Thanks a million and please continue the rewarding work.

  9. Hi my friend! I want to say that this article is amazing, nice written and include almost all vital infos. I would like to see more posts like this.

  10. I’m not that much of a internet reader to be honest but your sites really nice, keep it up! I’ll go ahead and bookmark your website to come back later on. Many thanks

  11. F*ckin? tremendous issues here. I?m very satisfied to see your article. Thanks a lot and i am looking ahead to touch you. Will you kindly drop me a e-mail?

  12. One other important aspect is that if you are an older person, travel insurance pertaining to pensioners is something you must really contemplate. The old you are, a lot more at risk you might be for allowing something awful happen to you while overseas. If you are definitely not covered by several comprehensive insurance coverage, you could have a few serious problems. Thanks for giving your advice on this web site.

  13. Magnificent beat ! I wish to apprentice at the same time as you amend your website, how can i subscribe for a blog website? The account helped me a appropriate deal. I had been tiny bit familiar of this your broadcast offered bright clear idea

  14. Simply desire to say your article is as amazing. The clearness in your post is just cool and i could assume you’re an expert on this subject. Fine with your permission let me to grab your feed to keep updated with forthcoming post. Thanks a million and please carry on the enjoyable work.

  15. Almost all of what you mention is astonishingly accurate and that makes me ponder why I had not looked at this in this light before. This particular piece really did turn the light on for me personally as far as this issue goes. However at this time there is one position I am not really too comfortable with and while I make an effort to reconcile that with the main theme of the position, let me see what the rest of your visitors have to point out.Very well done.

  16. Hey, I think your blog might be having browser compatibility issues. When I look at your blog in Ie, it looks fine but when opening in Internet Explorer, it has some overlapping. I just wanted to give you a quick heads up! Other then that, excellent blog!

  17. You can definitely see your expertise in the work you write. The sector hopes for more passionate writers like you who are not afraid to mention how they believe. Always follow your heart.

  18. Wow, this article is mind-blowing! The author has done a phenomenal job of conveying the information in an engaging and educational manner. I can’t thank him enough for providing such precious insights that have undoubtedly enriched my knowledge in this topic. Hats off to her for producing such a work of art!

  19. I have figured out some new elements from your web site about desktops. Another thing I have always believed is that laptop computers have become something that each residence must have for many reasons. They supply you with convenient ways to organize homes, pay bills, search for information, study, tune in to music and also watch tv programs. An innovative solution to complete every one of these tasks is a computer. These pc’s are mobile, small, powerful and mobile.

  20. Thanks for sharing your ideas. I would also like to express that video games have been ever before evolving. Better technology and inventions have helped create reasonable and active games. All these entertainment video games were not actually sensible when the real concept was being tried out. Just like other areas of technological know-how, video games way too have had to progress as a result of many years. This is testimony on the fast development of video games.

  21. excellent put up, very informative. I wonder why the opposite specialists of this sector do not understand this. You must proceed your writing. I’m sure, you’ve a huge readers’ base already!

  22. I loved as much as you will receive carried out right here. The sketch is attractive, your authored material stylish. nonetheless, you command get bought an shakiness over that you wish be delivering the following. unwell unquestionably come further formerly again as exactly the same nearly a lot often inside case you shield this increase.

  23. Hi there! Someone in my Facebook group shared this website with us so I came to give it a look. I’m definitely enjoying the information. I’m book-marking and will be tweeting this to my followers! Superb blog and terrific style and design.

  24. Howdy, i read your blog occasionally and i own a similar one and i was just wondering if you get a lot of spam comments? If so how do you prevent it, any plugin or anything you can recommend? I get so much lately it’s driving me insane so any help is very much appreciated.

  25. I have figured out some points through your site post. One other subject I would like to express is that there are several games that you can buy which are designed mainly for preschool age children. They incorporate pattern identification, colors, family pets, and patterns. These often focus on familiarization as an alternative to memorization. This will keep children occupied without having a sensation like they are studying. Thanks

  26. Thanks a lot for the helpful post. It is also my opinion that mesothelioma cancer has an very long latency time period, which means that symptoms of the disease won’t emerge right up until 30 to 50 years after the original exposure to mesothelioma. Pleural mesothelioma, that is certainly the most common style and impacts the area across the lungs, could cause shortness of breath, chest muscles pains, including a persistent coughing, which may bring on coughing up body.

  27. F*ckin? amazing things here. I am very glad to see your article. Thanks a lot and i’m looking forward to contact you. Will you kindly drop me a e-mail?

  28. Hi are using WordPress for your site platform? I’m new to the blog world but I’m trying to get started and set up my own. Do you require any coding knowledge to make your own blog? Any help would be really appreciated!

  29. You could certainly see your enthusiasm in the work you write. The sector hopes for more passionate writers like you who are not afraid to mention how they believe. At all times follow your heart.

發佈留言

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