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

11,262 Responses

  1. DouglasGed表示:

    medicine in mexico pharmacies: Certified Mexican pharmacy – purple pharmacy mexico price list

  2. A different issue is really that video gaming has become one of the all-time most important forms of excitement for people of any age. Kids participate in video games, and adults do, too. The XBox 360 has become the favorite games systems for people who love to have a lot of video games available to them, plus who like to play live with some others all over the world. Thank you for sharing your ideas.

  3. Thank you for every other great post. The place else may just anyone get that type of info in such an ideal way of writing? I’ve a presentation next week, and I am at the search for such information.

  4. DouglasGed表示:

    reputable indian pharmacies: top 10 pharmacies in india – buy medicines online in india

  5. Very great post. I simply stumbled upon your blog and wanted to mention that I’ve really loved surfing around your blog posts. In any case I?ll be subscribing to your rss feed and I am hoping you write once more very soon!

  6. DouglasGed表示:

    online ed treatments: cheap ed pills online – cheap ed meds online

  7. You actually make it seem really easy with your presentation but I in finding this topic to be really one thing which I believe I might by no means understand. It kind of feels too complicated and very extensive for me. I’m having a look ahead on your next post, I?ll try to get the hang of it!

  8. Michaelpoold表示:

    Benefits of mobile application
    pin-up bet download
    Today, it is very popular among gambling companies to create mobile applications for the users who use the phone the most. Many users download a pin-up program to take advantage of this program, which is the functionality of the browser version of the gambling platform.
    If you decide to download the Pin-up mobile application, you can use this application. The company’s employees care about the comfort of their users. The program has many fans from the world of gambling. The company has worked hard to develop the program.

    the profit

    intuitive interface;

    attractive design;

    Various sporting events and gambling entertainments;

    high speed of application;

    economical use of Internet traffic;

    Fixed access to the application, unlike the browser version.
    where to download apps for android

    There are several ways to download a pin-up program:

    The download file is downloaded directly from the official website of the virtual gambling company. This is the safest and most reliable method because you do not need to be afraid of scammers when downloading from the site;

    It is also recommended to download programs from third-party sites, but first you need to make sure that it is the original file, as scammers can offer you the wrong file.

    Downloading the file is very fast and simple, even the most inexperienced user can easily install this program. On the official website of the company there are detailed instructions on how to install the file on Android.

  9. Hi, Neat post. There’s a problem along with your web site in web explorer, might test this? IE still is the market leader and a huge section of other folks will pass over your magnificent writing because of this problem.

  10. Can you tell us this dog’s breed?

  11. This article is a refreshing change! The author’s unique perspective and thoughtful analysis have made this a truly engrossing read. I’m thankful for the effort he has put into creating such an enlightening and mind-stimulating piece. Thank you, author, for sharing your knowledge and sparking meaningful discussions through your exceptional writing!

  12. I believe one of your adverts caused my internet browser to resize, you might want to put that on your blacklist.

  13. Thank you for the good writeup. It in fact was a amusement account it. Look advanced to far added agreeable from you! However, how could we communicate?

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

  15. Thanks for your publication. What I want to comment on is that when searching for a good on the net electronics store, look for a web page with complete information on key elements such as the personal privacy statement, security details, payment procedures, and other terms plus policies. Always take time to browse the help along with FAQ pieces to get a much better idea of how the shop will work, what they are able to do for you, and ways in which you can make the most of the features.

  16. hello!,I like your writing very much! share we communicate more about your post on AOL? I require an expert on this area to solve my problem. May be that’s you! Looking forward to see you.

  17. Simply want to say your article is as amazing. The clarity to your submit is simply nice and i could think you are an expert in this subject. Well together with your permission let me to grasp your RSS feed to stay up to date with drawing close post. Thank you a million and please continue the rewarding work.

  18. Leonardpar表示:

    https://mexicopharmacy.win/# buying prescription drugs in mexico online

  19. Leonardpar表示:

    http://indiapharmacy.shop/# best online pharmacy india

  20. vo_ntorg_gyPt表示:

    Выбор всегда за вами: лучший арсенал для военных, покупайте.
    Оптимальное снаряжение для эффективных боевых действий, только у нас.
    Только лучшие модели военной техники, заказывайте.
    Как выбрать идеальное снаряжение для задач, используйте.
    Лучший выбор для военных операций: только качественное снаряжение, приобретайте.
    Выбор каждого воина: только лучшее оружие, приобретайте.
    Секрет успеха на поле боя: правильное снаряжение, только у проверенных поставщиков.
    Выбор профессионалов: только качественная техника, используйте.
    Оптимальное снаряжение для профессиональных военных действий, лишь у лучших.
    армійський магазин https://magazinvoentorgdcfr.kiev.ua/ .

  21. What?s Taking place i’m new to this, I stumbled upon this I’ve discovered It absolutely helpful and it has aided me out loads. I am hoping to give a contribution & aid different customers like its helped me. Great job.

  22. Thanks a lot for sharing this with all people you actually understand what you’re speaking approximately! Bookmarked. Kindly also discuss with my site =). We can have a link trade arrangement among us!

  23. Generally I do not read post on blogs, but I wish to say that this write-up very forced me to try and do it! Your writing style has been amazed me. Thanks, quite nice article.

  24. Wow, wonderful blog structure! How long have you ever been running a blog for? you make running a blog glance easy. The overall look of your website is wonderful, let alone the content material!

  25. Share market trading can be the good option against the inflation over the long term.

  26. Leonardpar表示:

    http://indiapharmacy.shop/# reputable indian online pharmacy

  27. hey there and thank you for your information ? I?ve certainly picked up something new from proper here. I did on the other hand experience a few technical points the usage of this website, as I experienced to reload the website a lot of instances prior to I could get it to load properly. I had been wondering if your web host is OK? Now not that I am complaining, but sluggish loading instances times will very frequently have an effect on your placement in google and could damage your high quality ranking if ads and ***********|advertising|advertising|advertising and *********** with Adwords. Anyway I am adding this RSS to my email and could look out for much extra of your respective intriguing content. Make sure you replace this once more soon..

  28. Shares also trade in Singapore, Hong Kong, and Tokyo.

  29. Cost of Consumer Durables Calculated as a cost to avoid double counting the value provided by the durables themselves.

發佈留言

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