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

32,575 Responses

  1. Rogertug表示:

    как установить Tor браузер – кракен маркетплейс, Kraken Market отзывы

  2. Hello I am so delighted I found your website, I really found you by mistake, while I was browsing on Google for something else, Anyhow I am here now and would just like to say thanks for a incredible post and a all round interesting blog (I also love the theme/design), I don’t have time to look over it all at the moment but I have saved it and also added your RSS feeds, so when I have time I will be back to read a great deal more, Please do keep up the great work.

  3. Derekgroum表示:

    Kamagra Gel: Kamagra Oral Jelly – Kamagra Gel

  4. Hmm is anyone else encountering problems with the images on this blog loading? I’m trying to figure out if its a problem on my end or if it’s the blog. Any suggestions would be greatly appreciated.

  5. You could definitely see your skills within the paintings you write. The sector hopes for even more passionate writers such as you who aren’t afraid to say how they believe. At all times follow your heart.

  6. Профессиональный сервисный центр по ремонту бытовой техники с выездом на дом.
    Мы предлагаем:сервисные центры в москве
    Наши мастера оперативно устранят неисправности вашего устройства в сервисе или с выездом на дом!

  7. Malcolmseern表示:

    Apotek hemleverans recept Apotek hemleverans idag Apotek hemleverans idag

  8. Rogertug表示:

    кракен даркнет – кракен актуальная ссылка, Kraken криптовалюта покупки

  9. Michaeltor表示:

    apotek online: Apotek hemleverans idag – Apoteket online

  10. Rogertug表示:

    тор браузер для доступа к даркнет – Кракен резервные ссылки 2025, Криптовалютные торговые площадки

  11. trc20 scan表示:

    I have noticed that online education is getting well-known because getting your degree online has developed into a popular choice for many people. Quite a few people have definitely not had a possibility to attend a normal college or university nonetheless seek the improved earning possibilities and a better job that a Bachelors Degree grants. Still other people might have a diploma in one discipline but would like to pursue anything they now develop an interest in.

  12. HomerFaw表示:

    https://apotheekmax.shop/# Betrouwbare online apotheek zonder recept

  13. Профессиональный сервисный центр по ремонту бытовой техники с выездом на дом.
    Мы предлагаем:сервисные центры в москве
    Наши мастера оперативно устранят неисправности вашего устройства в сервисе или с выездом на дом!

  14. Michaeltor表示:

    Betrouwbare online apotheek zonder recept: Apotheek Max – ApotheekMax

  15. Malcolmseern表示:

    apotek pa nett Apoteket online Apotek hemleverans recept

  16. I really appreciate this post. I have been looking everywhere for this! Thank goodness I found it on Bing. You have made my day! Thank you again

  17. raretron表示:

    Along with every little thing which seems to be building throughout this specific area, all your opinions happen to be fairly refreshing. On the other hand, I am sorry, because I can not give credence to your entire plan, all be it stimulating none the less. It appears to us that your comments are not totally validated and in reality you are generally your self not really fully certain of your assertion. In any event I did appreciate reading it.

  18. JeffreyVot表示:

    кракен безопасный вход – кракен площадка, как использовать VPN в даркнете

  19. magnificent points altogether, you just gained a new reader. What would you suggest about your post that you made a few days ago? Any positive?

  20. JeffreyVot表示:

    как попасть на kraken – Анонимные транзакции в интернете, Как использовать Tor для покупок

  21. 人気な国表示:

    The target value is based on game consequence 1, 0.5, or 0, with 0.5 being a draw.

  22. vanity wallet表示:

    You should participate in a contest for probably the greatest blogs on the web. I will recommend this website!

  23. rare trx表示:

    You can definitely see your expertise in the work you write. The arena hopes for even more passionate writers such as you who aren’t afraid to mention how they believe. Always go after your heart.

  24. Rogertug表示:

    кракен маркетплейс – кракен ссылка актуальная, vpn для безопасности в интернете

  25. trx generator表示:

    Along with the whole thing which seems to be building within this subject material, a significant percentage of viewpoints are actually rather stimulating. Even so, I beg your pardon, but I can not give credence to your entire theory, all be it refreshing none the less. It looks to everybody that your opinions are actually not entirely rationalized and in reality you are generally yourself not even totally convinced of the assertion. In any case I did appreciate reading it.

  26. Jamesavata表示:

    пин ап вход – пин ап казино официальный сайт

  27. Williamuniot表示:

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

  28. I would love to add that if you do not surely have an insurance policy or else you do not participate in any group insurance, you might well take advantage of seeking the aid of a health insurance broker. Self-employed or those that have medical conditions commonly seek the help of an health insurance brokerage. Thanks for your writing.

  29. I figured out more a new challenge on this fat reduction issue. One issue is a good nutrition is vital if dieting. An enormous reduction in bad foods, sugary ingredients, fried foods, sugary foods, red meat, and white flour products may perhaps be necessary. Retaining wastes parasites, and wastes may prevent desired goals for losing fat. While specific drugs temporarily solve the problem, the bad side effects are usually not worth it, plus they never supply more than a temporary solution. It’s a known idea that 95 of dietary fads fail. Many thanks sharing your notions on this blog.

  30. Hello! I know this is kinda off topic but I was wondering which blog platform are you using for this website? I’m getting sick and tired of WordPress because I’ve had problems with hackers and I’m looking at alternatives for another platform. I would be awesome if you could point me in the direction of a good platform.

發佈留言

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