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

  1. The almond toe, easy-on pull tab, and versatile rubber sole make it great for lengthy days on your toes in all kinds of weather.

  2. We know how troublesome packing for travel may be so we’ve written multiple articles that can assist you pack to your trip to Europe.

  3. Don’t fear, I’ve bought you coated.

  4. Having the Allbirds Tree Runners on foot actually allowed our toes to splay out properly.

  5. 株価 3639表示:

    Windchase coach Clara Lenhart has taken over the experience on Windchase Karat Gem; it will be enjoyable to see what she will do with this feisty redheaded mare – thus far they appear like an excellent match.

  6. A straightforward street opener spell with a candle and a Wiccan prayer.

  7. Do you need a pair of sneakers that are so versatile and lightweight that you can easily pack them if you journey?

  8. If you have a Tough State of affairs and wish quick and long lasting results, CONTACT ME NOW for a free session.

  9. 朱 読み方表示:

    Does Travel Insurance coverage Affect The Approval Of Visa Applications?

  10. 羽鳥手術表示:

    Gil, Richard. “Why Does Popcorn Value A lot at the Motion pictures?” PhysOrg.

  11. If the nomination of Ministers is conceded, it is on the ground that” Ministers appointed by the folks would necessarily be too highly esteemed.” The principle is that “the legislative body alone should possess the boldness of the people,” that royal authority corrupts its depository, and that govt energy is all the time tempted to commit abuses and to have interaction in conspiracies.

  12. They’re also super breathable and airy, which is nice for long, sweaty journey days.

  13. For some insurance policies there could also be a cap for the yr or for a specific illness declare.

  14. When bored with carrying it on one shoulder it would be shifted over to the opposite.

  15. Ensure that your health insurance covers all eventualities so that you’re by no means left in a susceptible place do you have to change into unwell.

  16. The location of the previous Camp de Vallejo was offered for housing and work began on a brand new stadium to the north of town in 1968.

  17. The flip to unions additionally belied the popular picture of digital-first media shops like VICE and Vox: laid-again workplaces staffed by younger, underpaid but happy writers, fueled by tech startups’ do-what-you-love, libertarian ethos, and housed in workplaces that look extra like nightclubs than newsrooms.

  18. Thailand really does appear just like the land of milk and honey for us.

  19. All bets are off, although, as soon as you eat the sort of brunch that has an omelet station, where a chef waits to cook to your order.

  20. Antlers might be modeled off any real life Antlers belonging to Deer, Moose, and so forth.

  21. There is a state of the art Bulthaup kitchen and Andrew says that he spent 10million on the rebuild.

  22. Though the rose petals would possibly make you assume “love,” this fortunate spell will provide help to attract good luck and abundance in all areas of your life.

  23. I have noticed that of all varieties of insurance, health care insurance is the most debatable because of the clash between the insurance policy company’s duty to remain making money and the customer’s need to have insurance cover. Insurance companies’ revenue on overall health plans are certainly low, thus some companies struggle to earn profits. Thanks for the ideas you discuss through this blog.

  24. Tabaq Restaurant focuses on offering a various range of Pakistani and South Asian delicacies, with a particular emphasis on its delectable kababs, aromatic biryanis, and flavorful curries.

  25. They stood, gazing upon the sun shining on the morning after, as the song was taking part in.

  26. We suggest to test along with your local embassies representing the nations that you’re touring to, as part of this itinerary.

  27. Although their value has fallen markedly and quality has improved over the last 10 years, most people won’t make this additional investment but.

  28. Black ballet flats are just what every lovely lady wants in her closet because they are so perfect for just about any outfit.

  29. How did Harry retrieve the sorcerer’s stone from the Mirror of Erised?

  30. Good Morning! My hope for all this stunning Thurday is joy in you hearts smiles in your faces Kindness in your hands and persistence stronger than your coffee!

發佈留言

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