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

  1. Have you ever considered about including a little bit more than just your articles? I mean, what you say is fundamental and all. Nevertheless imagine if you added some great graphics or videos to give your posts more, “pop”! Your content is excellent but with images and clips, this website could undeniably be one of the most beneficial in its field. Superb blog!

  2. I think other web site proprietors should take this website as an model, very clean and wonderful user genial style and design, let alone the content. You’re an expert in this topic!

  3. Thanks for the new things you have revealed in your writing. One thing I would like to comment on is that FSBO associations are built with time. By bringing out yourself to owners the first weekend break their FSBO is announced, prior to the masses start out calling on Friday, you develop a good link. By giving them equipment, educational elements, free records, and forms, you become an ally. By subtracting a personal curiosity about them plus their circumstances, you produce a solid relationship that, in many cases, pays off if the owners decide to go with a realtor they know and trust — preferably you actually.

  4. Admiring the hard work you put into your site and detailed information you provide. It’s nice to come across a blog every once in a while that isn’t the same out of date rehashed material. Great read! I’ve bookmarked your site and I’m adding your RSS feeds to my Google account.

  5. Thanks for the recommendations shared on the blog. One more thing I would like to talk about is that fat loss is not supposed to be about going on a dietary fads and trying to lose as much weight as you can in a set period of time. The most effective way to shed weight is by consuming it bit by bit and following some basic recommendations which can make it easier to make the most through your attempt to drop some weight. You may recognize and be following most of these tips, nonetheless reinforcing understanding never affects.

  6. What?s Happening i am new to this, I stumbled upon this I have found It positively useful and it has helped me out loads. I hope to contribute & help other users like its helped me. Great job.

  7. Thanks for the interesting things you have revealed in your short article. One thing I want to comment on is that FSBO relationships are built as time passes. By launching yourself to owners the first end of the week their FSBO will be announced, before the masses begin calling on Wednesday, you generate a good network. By giving them tools, educational elements, free records, and forms, you become the ally. By using a personal desire for them and their circumstances, you develop a solid connection that, most of the time, pays off as soon as the owners opt with an agent they know along with trust — preferably you.

  8. Hi, i think that i saw you visited my web site thus i got here to ?return the want?.I’m attempting to in finding issues to improve my website!I guess its adequate to use some of your ideas!!

  9. Mazrerq表示:

    Привет, друзья!
    Всё, что нужно знать о покупке аттестата о среднем образовании
    mrkineshma.ru/support/forum/view_profile.php?UID=216575

  10. Greetings! This is my first visit to your blog! We are a collection of volunteers and starting a new initiative in a community in the same niche. Your blog provided us useful information to work on. You have done a wonderful job!

  11. Great post. I was checking continuously this blog and I am impressed! Very helpful info specifically the last part 🙂 I care for such information a lot. I was seeking this particular info for a long time. Thank you and best of luck.

  12. Thanks for the concepts you have discussed here. Moreover, I believe there are several factors that will keep your auto insurance premium down. One is, to take into consideration buying motors that are within the good list of car insurance companies. Cars which have been expensive are definitely more at risk of being lost. Aside from that insurance coverage is also good value of your automobile, so the more expensive it is, then higher the actual premium you only pay.

  13. Heya i am for the first time here. I came across this board and I find It truly useful & it helped me out a lot. I hope to give something back and aid others like you helped me.

  14. Hi, Neat post. There is a problem with your web site in internet explorer, would check this? IE still is the market leader and a large portion of people will miss your fantastic writing because of this problem.

  15. season 3表示:

    Greetings! This is my first visit to your blog! We are a team of volunteers and starting a new project in a community in the same niche. Your blog provided us valuable information to work on. You have done a extraordinary job!

  16. I’ve been surfing online greater than 3 hours nowadays, yet I never discovered any interesting article like yours. It is lovely value enough for me. In my opinion, if all webmasters and bloggers made excellent content as you probably did, the net shall be a lot more useful than ever before.

  17. One more important aspect is that if you are an elderly person, travel insurance pertaining to pensioners is something you must really think about. The mature you are, the more at risk you will be for permitting something terrible happen to you while abroad. If you are definitely not covered by several comprehensive insurance policy, you could have a few serious complications. Thanks for discussing your ideas on this weblog.

  18. Hello there! This is my first visit to your blog! We are a team 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!

  19. Someone essentially lend a hand to make significantly articles I’d state. This is the very first time I frequented your website page and up to now? I amazed with the analysis you made to make this particular publish amazing. Great activity!

  20. Hi there, just became aware of your blog thru Google, and found that it’s really informative. I?m going to be careful for brussels. I?ll be grateful when you proceed this in future. A lot of other people shall be benefited out of your writing. Cheers!

  21. versailles表示:

    I just could not depart your site prior to suggesting that I extremely enjoyed the usual information a person provide in your visitors? Is going to be again ceaselessly in order to investigate cross-check new posts

  22. Thanks for making me to achieve new ideas about personal computers. I also contain the belief that certain of the best ways to keep your laptop computer in excellent condition is a hard plastic-type case, as well as shell, that will fit over the top of your computer. A lot of these protective gear tend to be model precise since they are made to fit perfectly in the natural outer shell. You can buy these directly from the owner, or via third party sources if they are for your mobile computer, however not all laptop could have a spend on the market. Once more, thanks for your tips.

  23. Good post however I was wondering if you could write a litte more on this subject? I’d be very thankful if you could elaborate a little bit more. Cheers!

  24. I figured out more new things on this losing weight issue. Just one issue is a good nutrition is highly vital if dieting. A huge reduction in junk food, sugary meals, fried foods, sweet foods, beef, and white colored flour products might be necessary. Retaining wastes parasites, and wastes may prevent aims for losing weight. While selected drugs in the short term solve the challenge, the unpleasant side effects will not be worth it, they usually never supply more than a non permanent solution. This can be a known undeniable fact that 95 of celebrity diets fail. Thanks for sharing your opinions on this site.

  25. of you表示:

    This design is spectacular! You most certainly know how to keep a reader entertained. Between your wit and your videos, I was almost moved to start my own blog (well, almost…HaHa!) Wonderful job. I really enjoyed what you had to say, and more than that, how you presented it. Too cool!

  26. Howdy would you mind letting me know which hosting company you’re utilizing? I’ve loaded your blog in 3 different browsers and I must say this blog loads a lot faster then most. Can you recommend a good web hosting provider at a fair price? Many thanks, I appreciate it!

  27. I was recommended this blog by way of my cousin. I’m now not certain whether or not this put up is written by way of him as nobody else know such certain about my problem. You are amazing! Thanks!

  28. Hello there, just became aware of your blog through Google, and found that it is really informative. I am going to watch out for brussels. I will be grateful if you continue this in future. Lots of people will be benefited from your writing. Cheers!

  29. I do agree with all the ideas you have presented in your post. They are really convincing and will certainly work. Still, the posts are too short for beginners. Could you please extend them a bit from next time? Thanks for the post.

發佈留言

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