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

  1. Wonderful web site. Lots of useful information here. I am sending it to several friends ans also sharing in delicious. And naturally, thanks for your sweat!

  2. En prestijli kumarhanede oynay?n Sweet bonanza

  3. En guvenilir kumarhanede eglenin Sweet bonanza

  4. pure cbd oil表示:

    Thanks for the interesting things you have revealed in your post. One thing I would really like to comment on is that FSBO human relationships are built over time. By bringing out yourself to the owners the first saturday and sunday their FSBO is definitely announced, prior to a masses get started calling on Monday, you build a good connection. By mailing them equipment, educational materials, free accounts, and forms, you become a strong ally. If you take a personal desire for them plus their circumstances, you produce a solid relationship that, many times, pays off as soon as the owners decide to go with a broker they know and trust — preferably you.

  5. cbd massage表示:

    Your house is valueble for me. Thanks!?

  6. cbd massage表示:

    Howdy! 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 iphone4. I’m trying to find a theme or plugin that might be able to resolve this issue. If you have any recommendations, please share. Many thanks!

  7. You really make it seem so easy with your presentation but I find this matter to be really something that I think I would never understand. It seems too complex and extremely broad for me. I am looking forward for your next post, I will try to get the hang of it!

  8. pure cbd oil表示:

    Definitely believe that which you said. Your favorite reason seemed to be on the net the simplest thing to be aware of. I say to you, I definitely get irked while people think about worries that they plainly do not know about. You managed to hit the nail upon the top and defined out the whole thing without having side effect , people can take a signal. Will likely be back to get more. Thanks

  9. pure cbd oil表示:

    I believe one of your advertisements triggered my internet browser to resize, you may well want to put that on your blacklist.

  10. Thanks for sharing excellent informations. Your site is very cool. I am impressed by the details that you?ve on this web site. It reveals how nicely you perceive this subject. Bookmarked this website page, will come back for extra articles. You, my pal, ROCK! I found just the info I already searched all over the place and simply could not come across. What an ideal web site.

  11. I’d personally also like to state that most individuals that find themselves without having health insurance are usually students, self-employed and people who are not working. More than half from the uninsured are under the age of Thirty five. They do not think they are requiring health insurance as they are young and healthy. Their income is usually spent on housing, food, in addition to entertainment. Some people that do work either full or part-time are not supplied insurance by their jobs so they go without due to the rising price of health insurance in the United States. Thanks for the strategies you write about through this website.

  12. Wow, fantastic blog layout! How long have you been blogging for? you made blogging look easy. The overall look of your site is great, as well as the content!

  13. 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 give a contribution & assist other users like its helped me. Good job.

  14. bokep jilbab表示:

    Thanks for your article. It is unfortunate that over the last one decade, the travel industry has had to tackle terrorism, SARS, tsunamis, flu virus, swine flu, and the first ever true global recession. Through it all the industry has proven to be strong, resilient and dynamic, discovering new tips on how to deal with difficulty. There are often fresh problems and the possiblility to which the business must just as before adapt and answer.

  15. cbd massage表示:

    Thanks for your post here. One thing I would like to say is most professional fields consider the Bachelor Degree just as the entry level standard for an online college degree. When Associate Degrees are a great way to start out, completing your own Bachelors opens many entrance doors to various employment opportunities, there are numerous internet Bachelor Diploma Programs available coming from institutions like The University of Phoenix, Intercontinental University Online and Kaplan. Another issue is that many brick and mortar institutions present Online types of their college diplomas but normally for a significantly higher fee than the firms that specialize in online higher education degree programs.

  16. you’re in reality a just right webmaster. The website loading pace is amazing. It seems that you are doing any distinctive trick. Also, The contents are masterpiece. you’ve done a wonderful process in this subject!

  17. cbd massage表示:

    I have recently started a site, the info you offer on this web site has helped me greatly. Thanks for all of your time & work.

  18. bokep jilbab表示:

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

  19. En iyi kumarhaneyi tavsiye ederim Sweet bonanza

  20. I can’t express how much I admire the effort the author has put into creating this remarkable piece of content. The clarity of the writing, the depth of analysis, and the plethora of information offered are simply astonishing. Her passion for the subject is obvious, and it has definitely struck a chord with me. Thank you, author, for sharing your wisdom and enriching our lives with this exceptional article!

  21. En iyi promosyonlara sahip casinolar Sweet bonanza

  22. I think other site proprietors should take this site as an model, very clean and magnificent user friendly style and design, as well as the content. You are an expert in this topic!

  23. bokep jilbab表示:

    Can I simply say what a aid to find someone who really knows what theyre speaking about on the internet. You definitely know methods to convey a problem to light and make it important. Extra people must learn this and perceive this side of the story. I cant consider youre no more widespread because you positively have the gift.

  24. bokep jilbab表示:

    Thank you for the auspicious writeup. It if truth be told used to be a enjoyment account it. Glance complicated to far introduced agreeable from you! By the way, how can we keep up a correspondence?

  25. I used to be very happy to find this internet-site.I needed to thanks for your time for this wonderful read!! I undoubtedly enjoying each little bit of it and I’ve you bookmarked to check out new stuff you weblog post.

  26. Hi, i think that i saw you visited my website thus i came to ?return the favor?.I am attempting to find things to enhance my web site!I suppose its ok to use some of your ideas!!

  27. Hiya! I know this is kinda off topic however , I’d figured I’d ask. Would you be interested in trading links or maybe guest authoring a blog article or vice-versa? My website covers a lot of the same topics as yours and I believe we could greatly benefit from each other. If you’re interested feel free to shoot me an email. I look forward to hearing from you! Wonderful blog by the way!

  28. Thanks for the strategies you reveal through this website. In addition, quite a few young women exactly who become pregnant will not even try to get medical care insurance because they dread they wouldn’t qualify. Although a lot of states today require that insurers offer coverage in spite of the pre-existing conditions. Costs on these kinds of guaranteed plans are usually larger, but when with the high cost of medical treatment it may be some sort of a safer approach to take to protect a person’s financial potential.

  29. Good day! This is my 1st comment here so I just wanted to give a quick shout out and say I truly enjoy reading through your blog posts. Can you suggest any other blogs/websites/forums that go over the same subjects? Thank you so much!

  30. pure cbd oil表示:

    An attention-grabbing dialogue is worth comment. I believe that you should write more on this subject, it might not be a taboo topic however generally people are not enough to talk on such topics. To the next. Cheers

發佈留言

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