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

16,511 Responses

  1. Thanks for your post here. One thing I would like to say is the fact most professional job areas consider the Bachelor Degree just as the entry level standard for an online course. When Associate Degrees are a great way to start, completing a person’s Bachelors presents you with many good opportunities to various professions, there are numerous internet Bachelor Course Programs available through institutions like The University of Phoenix, Intercontinental University Online and Kaplan. Another thing is that many brick and mortar institutions make available Online variants of their college diplomas but often for a significantly higher charge than the corporations that specialize in online college diploma programs.

  2. We make dwelling inspections straightforward with 24-hour on-line scheduling so you can also make an appointment at your comfort.

  3. Danieljek表示:

    amoxicillin tablet 500mg http://amoxilcompharm.com/# amoxicillin 500mg pill

  4. Lieutenant-Colonel Henry Valentine Bache De Satgé, CMG, CVO, DSO.

  5. Dereketerm表示:

    prednisone 21 pack: generic Prednisone – pharmacy cost of prednisone

  6. And i spoke to a Japanese family who instructed me how grateful they have been that they’d a chance to look around for what they thought was the easiest car for his or her family.

  7. Turkey has adopted a secular model of Christmas and a Santa Claus figure named Noel Baba (from the French Père Noël).

  8. For an all-purple gown, choose accents that are equally putting, comparable to eggplant purple flowers and black feathers for the bridal bouquet.

  9. Augustin and Plaine du Var by way of Lingostière.

  10. John Marriott Cole, Recently Principal Clerk, Supreme Court Taxing Workplace.

  11. Do you own any funding or other property?

  12. Combine them in with fashionable upholstery for a glance you can live with anywhere.

  13. The federal government has run an extensive co-design train in developing the SFS and remains to be in the strategy of consulting on the scheme, with no last decision to be made till after this session period.

  14. With that stated, someday, while scrolling through the rabbit hole that’s Pinterest one rainy afternoon, I stumbled throughout a plethora of “Pins” advertising easy methods to create a savings account and/or emergency fund in fifty two weeks (one 12 months) by following a detailed and outlined plan.

  15. When singing about someone she cannot have, Swift stated, “You’re so cool, it makes me hate you so much.” What track does this line belong to?

  16. It’s enough to maintain your canine hydrated without being an open source of water.

  17. To keep away from any danger- Make sure you lock your dog’s meals in a cabinet.- By no means depart the youngsters unsupervised with a canine.

  18. Did they ever clash in a Celtic-Rangers sport?

  19. Jupiter, the divine trainer, the embodiment of righteousness, information, and divinity, provides the right path, intuition, and inside guidance to Ketu, permitting one to entry limitless spiritual realizations and bliss.

  20. A moderately effectively-built shelter reduces intensity of external radiation and prevents fallout from settling on the animals’ bodies.

  21. And say what, precisely?

  22. Dry pet meals, especially pet food, is a choking hazard for young kids.

  23. In Might 2022, the again web page of the Every day Mail carried a story revealing Pep Guardiola’s curiosity within the France international – who was enjoying for Manchester United at the time – in what might have been probably the most explosive transfers in British soccer historical past.

  24. Wisdom solely begins once we let within the grief and rage of understanding climate breakdown.

發佈留言

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