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

  1. Leora表示:

    Here is my blog post – Find top-rated certified Daycares
    in your area (Leora)

  2. CharlesrooNo表示:

    Farmacie on line spedizione gratuita acquistare farmaci senza ricetta Farmacie on line spedizione gratuita

  3. Nice blog here! Also your website loads up fast! What host are you using? Can I get your affiliate link to your host? I wish my website loaded up as quickly as yours lol

  4. EdwardMet表示:

    viagra generico recensioni viagra farmacia viagra prezzo farmacia 2023

  5. I’d also like to state that most individuals who find themselves with no health insurance are usually students, self-employed and those that are not working. More than half on the uninsured are under the age of Thirty-five. They do not come to feel they are requiring health insurance simply because they’re young and also healthy. Their particular income is often spent on property, food, and entertainment. Some people that do work either entire or not professional are not made available insurance by way of their jobs so they go without owing to the rising cost of health insurance in the United States. Thanks for the concepts you share through this web site.

  6. I’m impressed by the quality of this content! The author has obviously put a great amount of effort into researching and organizing the information. It’s inspiring to come across an article that not only gives useful information but also keeps the readers hooked from start to finish. Kudos to him for producing such a remarkable piece!

  7. I have learn some just right stuff here. Certainly value bookmarking for revisiting. I wonder how much attempt you place to make one of these great informative site.

  8. Many thanks to you for sharing these types of wonderful posts. In addition, the perfect travel as well as medical insurance program can often eliminate those worries that come with visiting abroad. Your medical emergency can before long become expensive and that’s certain to quickly place a financial load on the family’s finances. Setting up in place the best travel insurance package prior to setting off is worth the time and effort. Thanks a lot

  9. Edisonanazy表示:

    comprare farmaci online con ricetta: Tadalafil generico migliore – farmacie online affidabili

  10. I’m not that much of a online reader to be honest but your blogs really nice, keep it up! I’ll go ahead and bookmark your site to come back in the future. Cheers

  11. Charlesmop表示:

    https://sildenafilit.pro/# viagra generico in farmacia costo
    farmaci senza ricetta elenco

  12. Charlesmop表示:

    https://sildenafilit.pro/# viagra originale in 24 ore contrassegno
    farmacia online senza ricetta

  13. Thinking lengthy-time period is nice.

  14. I defy anybody to take off their footwear after a hard day at work, slip on a pair of Uggs and never emit a suggestive sound of deep satisfaction.

  15. Briefly put, the environment friendly markets speculation states that prices of stocks, bonds, and other speculative belongings essentially reflect every part that is known about economic fundamentals, equivalent to inflation, exports, and company profitability.

  16. EdwardMet表示:

    comprare farmaci online all’estero Tadalafil generico migliore Farmacia online piГ№ conveniente

  17. LouisFoums表示:

    comprare farmaci online con ricetta: Cialis generico 20 mg 8 compresse prezzo – top farmacia online

  18. 7. Fascinating 14-page report about groundwater recharge in Texas rangeland, and also mentions how vegetation and soil conditions can have an effect on runoff.

  19. The president’s apparent desire to bankrupt the coal business is part of a two-step course of.

  20. Luggage are available in every size from a small nano dimension luggage to a giant large one for carrying wheat.

  21. LouisFoums表示:

    migliori farmacie online 2024: farmacia online migliore – farmacie online autorizzate elenco

  22. ro best表示:

    I loved up to you’ll receive performed proper here. The sketch is tasteful, your authored material stylish. however, you command get bought an edginess over that you want be turning in the following. in poor health indubitably come more formerly once more as exactly the same just about very often within case you defend this hike.

  23. This is a terrific site, would you be interested in doing an interview regarding just how you developed it? If so e-mail me!

  24. If the villa was the home of Joseph, then the surrounding huts might have been those of Joseph’s father and brothers.

  25. The Nike Shield line of sneakers are water-resistant so they’re a pleasant option in order for you sneakers that can be worn within the rain however nonetheless look cool.

  26. Hi! This is kind of off topic but I need some guidance from an established blog. Is it tough to set up your own blog? I’m not very techincal but I can figure things out pretty fast. I’m thinking about making my own but I’m not sure where to start. Do you have any tips or suggestions? Thanks

  27. There are some fascinating deadlines on this article however I don?t know if I see all of them center to heart. There may be some validity but I’ll take maintain opinion till I look into it further. Good article , thanks and we want extra! Added to FeedBurner as nicely

  28. Due to this, managed care plans are often extra inexpensive than FFS plans for similar ranges of protection.

  29. LouisFoums表示:

    farmacia online piГ№ conveniente: Cialis generico controindicazioni – farmaci senza ricetta elenco

  30. These footwear require some transition time, particularly if you’re used to the next heel drop, and they’re not beneficial for these with pre-present foot ache.

發佈留言

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