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

15,507 Responses

  1. Hi there! Would you mind if I share your blog with my myspace group? There’s a lot of people that I think would really appreciate your content. Please let me know. Thanks

  2. When I initially commented I clicked the “Notify me when new comments are added” checkbox and now each time a comment is added I get four emails with the same comment. Is there any way you can remove me from that service? Thanks a lot!

  3. I like what you guys are up also. Such smart work and reporting! Keep up the superb works guys I?ve incorporated you guys to my blogroll. I think it will improve the value of my website 🙂

  4. With havin so much content and articles do you ever run into any problems of plagorism or copyright infringement? My website has a lot of unique content I’ve either written myself or outsourced but it looks like a lot of it is popping it up all over the web without my permission. Do you know any solutions to help protect against content from being ripped off? I’d certainly appreciate it.

  5. I have learned some important things through your blog post. One other subject I would like to convey is that there are numerous games on the market designed specifically for preschool age kids. They incorporate pattern identification, colors, family pets, and models. These often focus on familiarization in lieu of memorization. This makes a child occupied without having the experience like they are learning. Thanks

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

  7. Scottdiz表示:

    1win официальный сайт: 1вин официальный сайт – 1вин сайт

  8. I have discovered some new things from your web-site about pc’s. Another thing I’ve always believed is that computers have become an item that each house must have for a lot of reasons. They provide convenient ways to organize the home, pay bills, search for information, study, listen to music as well as watch tv programs. An innovative approach to complete all of these tasks is by using a computer. These personal computers are mobile ones, small, powerful and easily transportable.

  9. Excellent weblog here! Additionally your web site so much up fast! What host are you the usage of? Can I get your associate link for your host? I want my web site loaded up as quickly as yours lol

  10. Отличный сайт! Всем рекомендую!запчасти в Минске

  11. Scottdaurf表示:

    пин ап казино вход: пин ап вход – пин ап казино вход

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

  13. Eanrvyw表示:

    Привет!
    Мы можем предложить дипломы любой профессии по приятным ценам.
    9020blog.com/board/blogs/2763/Why-is-the-popularity-of-universities-decreasing-all-the-time

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

  15. Sazrgqz表示:

    Купить диплом старого образца, можно ли это сделать по быстрой схеме?

    pipsgram.com/read-blog/94

  16. Warrenmof表示:

    https://pin-up.diy/# пин ап казино

  17. Scottdiz表示:

    1хбет официальный сайт: 1xbet зеркало – 1xbet зеркало рабочее на сегодня

  18. Hi, I think your site might be having browser compatibility issues. When I look at your website in Safari, 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, terrific blog!

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

  20. I cherished up to you will obtain carried out right here. The sketch is attractive, your authored subject matter stylish. nonetheless, you command get bought an nervousness over that you would like be turning in the following. unwell definitely come more until now once more since exactly the similar just about a lot incessantly inside of case you protect this increase.

  21. Scottdiz表示:

    vavada казино: вавада казино – казино вавада

  22. Thanks for the tips about credit repair on this excellent site. Some tips i would tell people is to give up the actual mentality they can buy at this point and pay out later. Being a society many of us tend to repeat this for many factors. This includes vacations, furniture, and items we would like. However, you must separate your current wants from the needs. As long as you’re working to boost your credit score actually you need some sacrifices. For example you may shop online to save cash or you can turn to second hand retailers instead of high-priced department stores regarding clothing.

  23. Hello my friend! I wish to say that this post is amazing, great written and include almost all significant infos. I?d like to peer more posts like this .

  24. Scottdaurf表示:

    pin up казино: пин ап вход – пин ап казино

  25. Scottdaurf表示:

    пин ап зеркало: пин ап вход – пин ап вход

發佈留言

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