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

  1. DanielTet表示:

    buy cytotec online fast delivery https://lipitor.guru/# lipitor 40 mg price in india
    lasix uses

  2. A person essentially help to make seriously posts I would state. This is the first time I frequented your web page and thus far? I amazed with the research you made to create this particular publish incredible. Fantastic job!

  3. I have observed that in the world today, video games include the latest trend with children of all ages. Often times it may be extremely hard to drag your family away from the video games. If you want the very best of both worlds, there are various educational video games for kids. Great post.

  4. Thanks for your interesting article. One other problem is that mesothelioma is generally caused by the inhalation of fibers from asbestos fiber, which is a dangerous material. It truly is commonly witnessed among staff in the building industry that have long exposure to asbestos. It is also caused by moving into asbestos insulated buildings for a long time of time, Family genes plays a huge role, and some people are more vulnerable for the risk when compared with others.

  5. Hey! I simply would like to give an enormous thumbs up for the good data you might have right here on this post. I will probably be coming again to your blog for extra soon.

  6. Thanks for the auspicious writeup. It actually was a enjoyment account it. Glance advanced to far brought agreeable from you! By the way, how can we communicate?

  7. Jamesric表示:

    lisinopril 20mg for sale: cheap lisinopril – lisinopril

  8. Hey! Do you use Twitter? I’d like to follow you if that would be okay. I’m absolutely enjoying your blog and look forward to new updates.

  9. Good write-up, I?m normal visitor of one?s site, maintain up the excellent operate, and It’s going to be a regular visitor for a long time.

  10. I like what you guys tend to be up too. This type of clever work and exposure! Keep up the superb works guys I’ve incorporated you guys to our blogroll.

  11. Even so, crowds of Romans grateful for an end to the Nazi occupation joyfully greeted the soldiers of U.S.

  12. Hey, you used to write fantastic, but the last several posts have been kinda boring? I miss your tremendous writings. Past few posts are just a little bit out of track! come on!

  13. CD sales were down 16 percent in the first half of 2008, with music stores closing and retailers reducing music space.

  14. I used to be suggested this website by my cousin. I am no longer certain whether this submit is written by means of him as nobody else realize such exact approximately my difficulty. You are wonderful! Thanks!

  15. We will have no choice but to backstop Europe through the IMF and pressuring China to do the same.

  16. Great ? I should certainly pronounce, impressed with your web site. I had no trouble navigating through all the tabs and related info ended up being truly easy to do to access. I recently found what I hoped for before you know it in the least. Reasonably unusual. Is likely to appreciate it for those who add forums or something, site theme . a tones way for your customer to communicate. Excellent task..

  17. There are some fascinating cut-off dates on this article however I don?t know if I see all of them middle to heart. There is some validity but I’ll take hold opinion till I look into it further. Good article , thanks and we would like more! Added to FeedBurner as well

  18. Thanks for your writing. I would also like to say that your health insurance dealer also works well with the benefit of the actual coordinators of a group insurance policies. The health broker is given a long list of benefits looked for by individuals or a group coordinator. What a broker does is try to find individuals as well as coordinators which will best go with those needs. Then he provides his referrals and if both sides agree, the particular broker formulates a legal contract between the 2 parties.

  19. Your house is valueble for me. Thanks!?

  20. Stephenzek表示:

    https://cytotec.pro/# buy cytotec over the counter

  21. Thank you for every other informative web site. Where else may I am getting that kind of info written in such an ideal manner? I have a project that I am just now running on, and I’ve been at the look out for such information.

  22. I believe that avoiding prepared foods would be the first step to lose weight. They may taste great, but highly processed foods possess very little nutritional value, making you take in more just to have enough energy to get through the day. For anyone who is constantly taking in these foods, switching to whole grain products and other complex carbohydrates will help you to have more strength while ingesting less. Good blog post.

  23. Stephenzek表示:

    http://furosemide.win/# furosemida 40 mg

  24. fantastic post, very informative. I’m wondering why the opposite specialists of this sector do not notice this. You should proceed your writing. I’m confident, you have a huge readers’ base already!

  25. Great work! That is the kind of info that are supposed to be shared around the internet. Shame on Google for not positioning this submit higher! Come on over and consult with my website . Thanks =)

  26. I simply couldn’t go away your website before suggesting that I really enjoyed the usual info an individual supply to your guests? Is gonna be back regularly in order to inspect new posts

  27. Good article. It’s very unfortunate that over the last years, the travel industry has had to handle terrorism, SARS, tsunamis, influenza, swine flu, and also the first ever entire global recession. Through everthing the industry has really proven to be powerful, resilient and dynamic, finding new strategies to deal with hardship. There are continually fresh difficulties and chance to which the sector must once more adapt and behave.

  28. I am no longer sure where you’re getting your info, however great topic. I must spend some time finding out much more or understanding more. Thank you for wonderful information I used to be looking for this info for my mission.

  29. This is very interesting, You’re a very skilled blogger. I have joined your rss feed and look forward to seeking more of your wonderful post. Also, I have shared your web site in my social networks!

發佈留言

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