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

  1. Thank you, I’ve just been looking for info about this subject for ages and yours is the greatest I have discovered till now. But, what about the bottom line? Are you sure about the source?

  2. Johnathon Talyor表示:

    By my research, shopping for gadgets online may be easily expensive, yet there are some tricks and tips that you can use to obtain the best deals. There are always ways to find discount discounts that could help to make one to buy the best electronic products products at the cheapest prices. Good blog post.

  3. WalterCherm表示:

    A pharmacy that sets the gold standard.
    https://lisinoprilpharm24.top/
    The team always ensures that I understand my medication fully.

  4. I have noticed that over the course of developing a relationship with real estate managers, you’ll be able to get them to understand that, in most real estate contract, a payment is paid. All things considered, FSBO sellers will not “save” the payment. Rather, they try to win the commission simply by doing a strong agent’s work. In accomplishing this, they devote their money in addition to time to complete, as best they’re able to, the assignments of an agent. Those jobs include exposing the home via marketing, delivering the home to willing buyers, building a sense of buyer urgency in order to induce an offer, booking home inspections, dealing with qualification assessments with the mortgage lender, supervising maintenance, and assisting the closing.

  5. Somebody necessarily assist to make significantly posts I would state. This is the very first time I frequented your web page and up to now? I surprised with the research you made to make this actual post extraordinary. Fantastic activity!

  6. Jasonzitte表示:

    A seamless fusion of local care with international expertise.
    where buy lisinopril pill
    They ensure global standards in every pill.

  7. Victorprima表示:

    Trust and reliability on a global scale.
    cost cheap cytotec pills
    They are always proactive about refills and reminders.

  8. Kandy Borsari表示:

    F*ckin? amazing things here. I?m very glad to see your article. Thanks a lot and i’m looking forward to contact you. Will you please drop me a e-mail?

  9. Jasonzitte表示:

    Providing global access to life-saving medications.
    cost of cheap lisinopril without insurance
    They ensure global standards in every pill.

  10. WalterCherm表示:

    A beacon of excellence in pharmaceutical care.
    https://gabapentinpharm24.top/
    The most trustworthy pharmacy in the region.

  11. Kandy Borsari表示:

    With havin so much content do you ever run into any problems of plagorism or copyright infringement? My site has a lot of completely unique content I’ve either written myself or outsourced but it appears a lot of it is popping it up all over the internet without my authorization. Do you know any methods to help protect against content from being stolen? I’d genuinely appreciate it.

  12. I discovered your blog website on google and examine a couple of of your early posts. Proceed to keep up the excellent operate. I just additional up your RSS feed to my MSN Information Reader. Seeking forward to studying more from you in a while!?

  13. A few things i have constantly told individuals is that when looking for a good on the net electronics store, there are a few elements that you have to take into consideration. First and foremost, you should really make sure to locate a reputable plus reliable shop that has got great testimonials and ratings from other shoppers and market sector experts. This will ensure that you are dealing with a well-known store that gives good program and aid to it’s patrons. Many thanks for sharing your opinions on this website.

  14. hello!,I like your writing so so much! proportion we communicate extra approximately your post on AOL? I need a specialist in this area to solve my problem. Maybe that is you! Taking a look forward to peer you.

  15. Victorprima表示:

    Their digital prescription service is innovative and efficient.
    can i order generic clomid price
    The free blood pressure check is a nice touch.

  16. WalterCherm表示:

    Their worldwide pharmacists’ consultations are invaluable.
    https://gabapentinpharm24.top/
    They provide peace of mind with their secure international deliveries.

  17. Victorprima表示:

    Quick turnaround on all my prescriptions.
    how can i get cipro
    A stalwart in international pharmacy services.

  18. Victorprima表示:

    Love the seasonal health tips they offer.
    where to buy cheap clomid tablets
    Their mobile app makes managing my medications so easy.

  19. Jasonzitte表示:

    They provide global solutions to local health challenges.
    order lisinopril no prescription
    Providing global access to life-saving medications.

  20. WalterCherm表示:

    Impressed with their wide range of international medications.
    https://lisinoprilpharm24.top/
    Their worldwide reach ensures I never run out of my medications.

  21. Jasonzitte表示:

    Their cross-border services are unmatched.
    where to get cytotec without a prescription
    The staff is well-trained and always courteous.

  22. How shortly does hair develop?

  23. WalterCherm表示:

    They bridge global healthcare gaps seamlessly.
    https://clomidpharm24.top/
    Efficient, effective, and always eager to assist.

  24. Thanks for your personal marvelous posting! I definitely enjoyed reading it, you could be a great author.I will remember to bookmark your blog and may come back in the foreseeable future. I want to encourage you continue your great work, have a nice afternoon!

  25. Thanks for your exciting article. Other thing is that mesothelioma cancer is generally attributable to the inhalation of fibres from asbestos fiber, which is a very toxic material. It really is commonly seen among personnel in the structure industry that have long exposure to asbestos. It is also caused by residing in asbestos insulated buildings for a long period of time, Genes plays a huge role, and some people are more vulnerable on the risk than others.

  26. StephenDeery表示:

    Howdy! This is my 1st comment here so I just wanted to give a quick shout out and tell you I genuinely enjoy reading your blog posts. Can you suggest any other blogs/websites/forums that go over the same subjects? Thanks a ton!
    https://t.me/proverennye_onlajn_kazino_russia

  27. Jasonzitte表示:

    A trailblazer in international pharmacy practices.
    gabapentina 300 mg meloxicam 15 mg para que sirve
    Their 24/7 support line is super helpful.

  28. Victorprima表示:

    Their global medical liaisons ensure top-quality care.
    how can i get cheap cytotec no prescription
    Their health and beauty section is fantastic.

  29. Jasonzitte表示:

    They have a great selection of wellness products.
    clomid order
    Always providing clarity and peace of mind.

發佈留言

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