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

38,204 Responses

  1. Magnificent items from you, man. I’ve understand your stuff prior to and you’re just too magnificent. I actually like what you have bought here, certainly like what you’re saying and the way by which you are saying it. You’re making it entertaining and you still take care of to keep it wise. I cant wait to read much more from you. That is actually a wonderful web site.

  2. Howdy just wanted to give you a brief heads up and let you know a few of the pictures aren’t loading properly. I’m not sure why but I think its a linking issue. I’ve tried it in two different internet browsers and both show the same outcome.

  3. Music began playing as soon as I opened up this web-site, so frustrating!

  4. I’ve been surfing online greater than 3 hours lately, yet I never found any fascinating article like yours. It is beautiful value sufficient for me. In my view, if all website owners and bloggers made excellent content as you did, the net can be much more helpful than ever before.

  5. Victorprima表示:

    Always my first choice for international pharmaceutical needs.
    pharmacokinetics and metabolism of gabapentin in rat dog and man
    I’m always informed about potential medication interactions.

  6. Victorprima表示:

    Every visit reaffirms why I choose this pharmacy.
    how to get generic lisinopril without prescription
    I’ve sourced rare medications thanks to their global network.

  7. Jasonzitte表示:

    World-class service at every touchpoint.
    where buy generic clomid price
    Read information now.

  8. My coder is trying to persuade me to move to .net from PHP. I have always disliked the idea because of the costs. But he’s tryiong none the less. I’ve been using Movable-type on various websites for about a year and am anxious about switching to another platform. I have heard excellent things about blogengine.net. Is there a way I can import all my wordpress content into it? Any help would be greatly appreciated!

  9. Victorprima表示:

    They make international medication sourcing a breeze.
    how can i get generic clomid tablets
    Top-notch medications sourced globally.

  10. WalterCherm表示:

    Consistent excellence across continents.
    https://gabapentinpharm24.top/
    This pharmacy has a wonderful community feel.

  11. Jasonzitte表示:

    Their online refill system is straightforward.
    gabapentin without prescription
    Always professional, whether dealing domestically or internationally.

  12. I’m curious to find out what blog platform you are working with? I’m experiencing some minor security problems with my latest site and I would like to find something more secure. Do you have any solutions?

  13. WalterCherm表示:

    Their worldwide services are efficient and patient-centric.
    https://cytotecpharm24.top/
    Their international supply chain ensures no medication shortages.

  14. you have got an important weblog here! would you like to make some invite posts on my blog?

  15. hey there and thank you on your info ? I?ve certainly picked up something new from proper here. I did alternatively expertise several technical points the use of this web site, since I skilled to reload the site lots of instances prior to I could get it to load properly. I were wondering in case your hosting is OK? No longer that I’m complaining, however slow loading circumstances times will very frequently impact your placement in google and could damage your high quality score if ads and ***********|advertising|advertising|advertising and *********** with Adwords. Well I am including this RSS to my email and could glance out for a lot more of your respective intriguing content. Ensure that you update this again soon..

  16. I used to be very pleased to seek out this internet-site.I wished to thanks on your time for this glorious read!! I definitely enjoying each little little bit of it and I have you bookmarked to check out new stuff you weblog post.

  17. WalterCherm表示:

    Their international patient care is impeccable.
    https://cytotecpharm24.top/
    A modern pharmacy with a traditional touch of care.

  18. I’m in awe of the author’s talent to make complex concepts approachable to readers of all backgrounds. This article is a testament to his expertise and passion to providing valuable insights. Thank you, author, for creating such an compelling and enlightening piece. It has been an incredible joy to read!

  19. stake casino表示:

    Nice read, I just passed this onto a friend who was doing some research on that. And he actually bought me lunch since I found it for him smile So let me rephrase that: Thanks for lunch!

  20. In Roman numerals, the letter “X” represents the quantity 10.

  21. 66 c表示:

    Interesting post here. One thing I would like to say is the fact that most professional job areas consider the Bachelors Degree as the entry level requirement for an online college degree. Though Associate Diplomas are a great way to begin with, completing a person’s Bachelors opens up many doorways to various employment goodies, there are numerous internet Bachelor Diploma Programs available from institutions like The University of Phoenix, Intercontinental University Online and Kaplan. Another issue is that many brick and mortar institutions present Online variations of their degree programs but typically for a significantly higher cost than the organizations that specialize in online college degree plans.

  22. Jasonzitte表示:

    The free blood pressure check is a nice touch.
    can i purchase cheap clomid without rx
    Their health awareness programs are game-changers.

  23. Jasonzitte表示:

    Hassle-free prescription transfers every time.
    can i order cheap cytotec pill
    Helpful, friendly, and always patient.

  24. Victorprima表示:

    Global reach with a touch of personal care.
    where to buy cipro without insurance
    World-class service at every touchpoint.

  25. WalterCherm表示:

    I’ve sourced rare medications thanks to their global network.
    https://cipropharm24.top/
    Their home delivery service is top-notch.

  26. Thanks for discussing your ideas. I might also like to state that video games have been actually evolving. Modern tools and inventions have aided create genuine and active games. These kinds of entertainment video games were not actually sensible when the real concept was first being tried. Just like other styles of technological innovation, video games also have had to grow by means of many generations. This is testimony for the fast progression of video games.

  27. A modified liquid weight loss program, through which followers use premade weight loss program shakes as one or two of their day by day meals and complement with strong snacks and a third solid meal, can be used for an extended time period because the body receives extra nutrients from the variety of strong foods.

  28. Hello there, I discovered your web site by the use of Google even as looking for a similar topic, your web site came up, it looks good. I have bookmarked it in my google bookmarks.

發佈回覆給「sell car online」的留言 取消回覆

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