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

  1. click here表示:

    hello there and thanks to your information ? I have certainly picked up anything new from right here. I did however experience a few technical issues using this website, as I skilled to reload the web site many times prior to I may just get it to load correctly. I were pondering in case your hosting is OK? No longer that I’m complaining, but sluggish loading cases times will often affect your placement in google and can damage your high quality score if ads and ***********|advertising|advertising|advertising and *********** with Adwords. Well I am including this RSS to my email and can glance out for a lot more of your respective exciting content. Make sure you replace this once more soon..

  2. Danger control incorporates, starting of change control demands when changes in risk status or risk plan could influence the accessibility of the administration or service level agreement.

  3. JamesLok表示:

    Slot dengan grafis 3D sangat mengesankan http://preman69.tech/# Kasino selalu memperbarui mesin slotnya

  4. Williecrady表示:

    Beberapa kasino memiliki area khusus untuk slot http://slotdemo.auction/# Pemain harus memahami aturan masing-masing mesin

  5. DavidCooth表示:

    http://bonaslot.site/# Kasino sering mengadakan turnamen slot menarik

  6. Предлагаем услуги профессиональных инженеров офицальной мастерской.
    Еслли вы искали ремонт фотоаппаратов canon в москве, можете посмотреть на сайте: ремонт фотоаппаратов canon
    Наши мастера оперативно устранят неисправности вашего устройства в сервисе или с выездом на дом!

  7. DavidCooth表示:

    http://bonaslot.site/# Slot dengan tema film terkenal menarik banyak perhatian

  8. ThomasThype表示:

    Mesin slot menawarkan pengalaman bermain yang cepat: bonaslot.site – BonaSlot

  9. Aaronbus表示:

    BonaSlot bonaslot.site Mesin slot baru selalu menarik minat

  10. Предлагаем услуги профессиональных инженеров офицальной мастерской.
    Еслли вы искали ремонт фотоаппаратов canon сервис, можете посмотреть на сайте: ремонт фотоаппаратов canon цены
    Наши мастера оперативно устранят неисправности вашего устройства в сервисе или с выездом на дом!

  11. In this article, we’ll explore the varied symbolic meanings attached to bird droppings and delve into the spiritual significance behind this seemingly mundane act.

  12. Откройте двери в роскоши и страсти, где возможно всё. Наш Telegram-канал “Проститутки Москва” приветствует вас вас ждет изысканный ассортимент самых восхитительных и желанных девушек Москвы. Мы убеждены, что каждый момент — это путь к новым открытиям и ощутить изысканность и комфорт.

    Москва — это не просто столица, но и центр притяжения, где Эскортницы ждут вас. У нас вы найдете только лучших профессионалов в сфере сопровождения, желающих подарить вам праздник. С нами просто организовать встречу с Проститутки вашей мечты.

    Шлюхи, представленные в нашем канале, обладают не только выдающейся внешностью, но и талантом делать каждый момент особенным. Они понимают ваши желания, и предложит вам незабываемое время. Обращаясь к нам, вы оцениваете высокий уровень обслуживания, полную конфиденциальность и уверенность. что время, проведенное вместе, останется в вашей памяти.

    Проститутки, отобранные для вас, подвергаются тщательной проверке, чтобы предоставить вам лучший сервис. Будьте спокойны за их навыки и ответственность. Каждая из них — это не только шикарная упаковка, но и умение вовлечь вас в мир наслаждения. С помощью нашего канала вы без труда посмотрите профили, найти ту, которая вам подойдет и оперативно запланировать свидание.

    Telegram-канал “Проститутки Москва” ваш проводник в мир наслаждений. Мы понимаем, что каждый клиент уникален, поэтому предлагаем только самые разнообразные варианты, чтобы угодить каждому. Здесь вы найдете как утонченных эскортниц, так и более смелых индивидуалок, которые добавят перчинку в вашу жизнь.

    Вырвитесь из обыденности и почувствуйте себя в мире роскоши и комфорта. Вызовите Эскортницы из нашего канала, и вы увидите, насколько яркой может быть ваша жизнь. Воспользуйтесь возможностью испытать все прелести встреч с лучшими красавицами Москвы, которые с нетерпением ждут вас.

    Узнайте больше по ссылке: https://t.me/s/Official_girl_msk и выберите ту, которая покорит вас. Откройте для себя мир новых впечатлений, которые останутся в вашей памяти навсегда. Проститутки готовы встретиться с вами, чтобы ваш вечер был незабываемым.

    Окунитесь в мир удовольствий и сделайте свою жизнь ярче. Москва – это город, который никогда не спит, и мы покажем вам все самое интересное. Пришло время побаловать себя — доверяйте профессионалам, вызывайте тех, кто способен подарить вам поистине уникальный опыт.

    Пусть ваши желания сбываются с нашими восхитительными девушками, и каждый вечер будет особенным. Вместе с “Проститутки Москва” ваши мечты станут реальностью в самом центре Москвы.

  13. ThomasThype表示:

    Kasino menawarkan pengalaman bermain yang seru: garuda888 – garuda888

  14. GreggRom表示:

    A brief history of sunglasses, from Ancient Rome to Hollywood
    kraken сайт

    Sunglasses, or dark glasses, have always guarded against strong sunlight, but is there more to “shades” than we think?

    The pupils of our eyes are delicate and react immediately to strong lights. Protecting them against light — even the brilliance reflected off snow — is important for everyone. Himalayan mountaineers wear goggles for this exact purpose.

    Protection is partly the function of sunglasses. But dark or colored lens glasses have become fashion accessories and personal signature items. Think of the vast and famous collector of sunglasses Elton John, with his pink lensed heart-shaped extravaganzas and many others.

    When did this interest in protecting the eyes begin, and at what point did dark glasses become a social statement as well as physical protection?
    The Roman Emperor Nero is reported as holding polished gemstones to his eyes for sun protection as he watched fighting gladiators.

    We know Canadian far north Copper Inuit and Alaskan Yupik wore snow goggles of many kinds made of antlers or whalebone and with tiny horizontal slits. Wearers looked through these and they were protected against the snow’s brilliant light when hunting. At the same time the very narrow eye holes helped them to focus on their prey.

    In 12th-century China, judges wore sunglasses with smoked quartz lenses to hide their facial expressions — perhaps to retain their dignity or not convey emotions.

  15. Williecrady表示:

    Slot dengan tema budaya lokal menarik perhatian http://slotdemo.auction/# Pemain bisa menikmati slot dari kenyamanan rumah

  16. Aaronbus表示:

    bonaslot.site bonaslot Slot dengan tema budaya lokal menarik perhatian

  17. Williecrady表示:

    Slot menjadi bagian penting dari industri kasino https://preman69.tech/# Pemain harus memahami aturan masing-masing mesin

  18. learn more表示:

    A few things i have observed in terms of computer memory is that there are requirements such as SDRAM, DDR etc, that must go with the specifications of the mother board. If the pc’s motherboard is reasonably current while there are no operating-system issues, improving the memory literally normally takes under a couple of hours. It’s one of the easiest laptop upgrade techniques one can consider. Thanks for expressing your ideas.

  19. ThomasThype表示:

    Slot klasik tetap menjadi favorit banyak orang: garuda888 – garuda888

  20. WilliamSed表示:

    About us
    Since its founding in 2020, EtherCode Innovation has demonstrated an outstanding level of expertise in smart contract development on the Ethereum platform. The EtherCode Innovation team brings together experienced developers whose knowledge and skills allow them to create reliable and innovative solutions for their clients
    eth honeypot code
    Mission
    We strive to ensure that every person interested in blockchain technologies can gain high-quality knowledge and skills. Our mission is to develop smart contracts that not only improve the functionality of the Ethereum network, but also contribute to the education and development of the developer community.

    Our services
    EtherCode Innovation specializes in creating various smart contracts within Ethereum. We develop innovative solutions for financial instruments, decentralized applications (DApps) and digital asset management systems. Our team has deep knowledge of the Solidity and Vyper programming languages, which allows us to create secure and efficient smart contracts.

    In addition, we provide free educational content for those who want to learn how to create tokens, including Honeypot tokens. Our materials cover all aspects of creating and deploying tokens on Ethereum, from basic concepts to complex technical details.

    Our contribution to the community
    We believe that education plays a key role in the development of the blockchain community. Therefore, we actively participate in various educational and communication initiatives. We also support various educational projects aimed at spreading knowledge about blockchain.

    Development prospects
    We are confident that blockchain technology will continue to transform the world, and we are committed to staying at the center of this process. Our team will continue to create innovative products, develop educational resources, and actively participate in the development of the Ethereum developer community.

    Finally, it is worth noting that EtherCode Innovation is committed to continuous development and innovation. The team is constantly researching new technologies and development methods to provide its clients with the most advanced solutions. Thanks to this approach, the company remains ahead of its time and continues to be in demand in the field of blockchain development.

    EtherCode Innovation is not just a company developing smart contracts on Ethereum. We are leaders in blockchain technology and education, and we invite you to join us on this exciting journey into the world of decentralization and innovation.

  21. JamesLok表示:

    Slot memberikan kesempatan untuk menang besar https://slot88.company/# Banyak pemain mencari mesin dengan RTP tinggi

  22. You can’t add playing cards to your opponents’ melds.

  23. DavidCooth表示:

    http://slot88.company/# Kasino di Indonesia menyediakan hiburan yang beragam

  24. DavidCooth表示:

    http://garuda888.top/# Bermain slot bisa menjadi pengalaman sosial

  25. ThomasThype表示:

    Permainan slot mudah dipahami dan menyenangkan: slot demo gratis – demo slot pg

  26. ThomasThype表示:

    Kasino menawarkan pengalaman bermain yang seru: preman69 – preman69 slot

  27. Williecrady表示:

    Kasino mendukung permainan bertanggung jawab https://slotdemo.auction/# Kasino memastikan keamanan para pemain dengan baik

  28. Предлагаем услуги профессиональных инженеров офицальной мастерской.
    Еслли вы искали ремонт фотоаппаратов canon рядом, можете посмотреть на сайте: ремонт фотоаппаратов canon
    Наши мастера оперативно устранят неисправности вашего устройства в сервисе или с выездом на дом!

  29. Aaronbus表示:

    demo slot pg slot demo rupiah Kasino sering mengadakan turnamen slot menarik

  30. JamesLok表示:

    Slot menawarkan berbagai jenis permainan bonus https://preman69.tech/# Banyak pemain menikmati jackpot harian di slot

發佈回覆給「DavidCooth」的留言 取消回覆

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