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

  1. gay porn表示:

    Hola! I’ve been reading your weblog for some time now and finally got the bravery to go ahead and give you a shout out from Lubbock Tx! Just wanted to tell you keep up the fantastic job!

  2. RamonRek表示:

    semaglutide tablets: semaglutide online – buy rybelsus online

  3. Jeremypag表示:

    ozempic cost ozempic online buy ozempic pills online

  4. Thanks for the different tips discussed on this blog. I have observed that many insurance agencies offer customers generous savings if they choose to insure more and more cars with them. A significant variety of households have several vehicles these days, especially those with mature teenage young children still living at home, along with the savings upon policies can certainly soon mount up. So it pays to look for a good deal.

  5. HaroldBig表示:

    ozempic: ozempic online – ozempic

  6. Greetings from Los angeles! I’m bored at work so I decided to check out your site on my iphone during lunch break. I love the info you present here and can’t wait to take a look when I get home. I’m amazed at how quick your blog loaded on my cell phone .. I’m not even using WIFI, just 3G .. Anyways, great site!

  7. I have noticed that over the course of building a relationship with real estate proprietors, you’ll be able to get them to understand that, in every real estate deal, a fee is paid. Finally, FSBO sellers tend not to “save” the commission rate. Rather, they try to earn the commission by way of doing an agent’s work. In doing this, they commit their money plus time to carry out, as best they are able to, the obligations of an representative. Those jobs include disclosing the home by marketing, showing the home to buyers, building a sense of buyer emergency in order to induce an offer, booking home inspections, handling qualification check ups with the loan provider, supervising maintenance tasks, and aiding the closing of the deal.

  8. BarryDof表示:

    https://ozempic.art/# ozempic generic

  9. pravo752obliz表示:

    Тут можно получить качественные Услуги юриста.

  10. online casino表示:

    Attractive section of content. I just stumbled upon your site and in accession capital to assert that I get actually enjoyed account your blog posts. Any way I will be subscribing to your augment and even I achievement you access consistently quickly.

  11. Thanks for your article. Another thing is that being photographer will involve not only issues in catching award-winning photographs but in addition hardships in establishing the best digicam suited to your needs and most especially struggles in maintaining the quality of your camera. This is certainly very accurate and clear for those photography lovers that are directly into capturing a nature’s exciting scenes – the mountains, the particular forests, the particular wild or perhaps the seas. Visiting these exciting places certainly requires a camera that can meet the wild’s unpleasant setting.

  12. RobertWaf表示:

    Arrowheads reveal the presence of a mysterious army in Europe’s oldest battle
    гей порно молодые
    Today, the lush, green valley surrounding the Tollense River in northeast Germany appears to be a serene place to appreciate nature.

    But to archaeologists, the Tollense Valley is considered Europe’s oldest battlefield.

    An amateur archaeologist first spotted a bone sticking out of the riverbank in 1996.

    A series of ongoing site excavations since 2008 has shown that the thousands of bones and hundreds of weapons preserved by the valley’s undisturbed environment were part of a large-scale battle 3,250 years ago.

    The biggest mysteries that researchers aim to uncover are why the battle occurred and who fought in it. These are questions that they are now one step closer to answering.
    ozens of bronze and flint arrowheads recovered from the Tollense Valley are revealing details about the able-bodied warriors who fought in the Bronze Age battle.

    The research team analyzed and compared the arrowheads, some of which were still embedded in the remains of the fallen. While many of these weapons were locally produced, some bearing different shapes came from a region that now includes modern Bavaria and Moravia.

    The outliers’ presence suggests that a southern army clashed with local tribes in the valley, and researchers suspect the conflict began at a key landmark along the river.

    Back to the future
    Scientists are harnessing the power of artificial intelligence to detect hidden archaeological sites buried below the sand of the sprawling Rub‘ al-Khali desert.

    The desert spans 250,000 square miles (650,000 square kilometers) on the Arabian Peninsula, and its name translates to “the Empty Quarter” in English. To unravel the secrets of the desolate terrain, researchers are combining machine learning with a satellite imagery technique that uses radio waves to spot objects that may be concealed beneath surfaces.

    The technology will be tested in October when excavations assess whether predicted structures are present at the Saruq Al Hadid complex in Dubai, United Arab Emirates.

    Separately, an AI-assisted analysis uncovered a trove of ancient symbols in Peru’s Nazca Desert, nearly doubling the number of known geoglyphs, or stone and gravel arranged into giant shapes that depict animals, humans and geometric designs.

  13. I have seen that wise real estate agents almost everywhere are Promoting. They are noticing that it’s more than simply placing a sign in the front place. It’s really about building interactions with these traders who later will become buyers. So, whenever you give your time and energy to assisting these dealers go it alone : the “Law involving Reciprocity” kicks in. Good blog post.

  14. Porn video表示:

    Howdy are using WordPress for your blog platform? I’m new to the blog world but I’m trying to get started and create my own. Do you require any html coding knowledge to make your own blog? Any help would be really appreciated!

  15. I will immediately grab your rss as I can’t to find your e-mail subscription link or newsletter service. Do you have any? Kindly permit me understand in order that I may just subscribe. Thanks.

  16. One thing is the fact one of the most common incentives for using your card is a cash-back or even rebate present. Generally, you will get 1-5 back with various expenses. Depending on the cards, you may get 1 back again on most buying, and 5 back again on purchases made using convenience stores, gas stations, grocery stores and also ‘member merchants’.

  17. Charlesrab表示:

    Pharmacie sans ordonnance Medicaments en ligne livres en 24h Achat mГ©dicament en ligne fiable

  18. online casino表示:

    I should say also believe that mesothelioma is a scarce form of melanoma that is commonly found in all those previously familiar with asbestos. Cancerous cellular material form from the mesothelium, which is a shielding lining that covers most of the body’s body organs. These cells typically form within the lining of your lungs, abdominal area, or the sac that encircles one’s heart. Thanks for expressing your ideas.

  19. Stephengen表示:

    https://pharmaciepascher.pro/# pharmacie en ligne pas cher

  20. Jeffreygef表示:

    Arrowheads reveal the presence of a mysterious army in Europe’s oldest battle
    жесткое порно
    Today, the lush, green valley surrounding the Tollense River in northeast Germany appears to be a serene place to appreciate nature.

    But to archaeologists, the Tollense Valley is considered Europe’s oldest battlefield.

    An amateur archaeologist first spotted a bone sticking out of the riverbank in 1996.

    A series of ongoing site excavations since 2008 has shown that the thousands of bones and hundreds of weapons preserved by the valley’s undisturbed environment were part of a large-scale battle 3,250 years ago.

    The biggest mysteries that researchers aim to uncover are why the battle occurred and who fought in it. These are questions that they are now one step closer to answering.
    ozens of bronze and flint arrowheads recovered from the Tollense Valley are revealing details about the able-bodied warriors who fought in the Bronze Age battle.

    The research team analyzed and compared the arrowheads, some of which were still embedded in the remains of the fallen. While many of these weapons were locally produced, some bearing different shapes came from a region that now includes modern Bavaria and Moravia.

    The outliers’ presence suggests that a southern army clashed with local tribes in the valley, and researchers suspect the conflict began at a key landmark along the river.

    Back to the future
    Scientists are harnessing the power of artificial intelligence to detect hidden archaeological sites buried below the sand of the sprawling Rub‘ al-Khali desert.

    The desert spans 250,000 square miles (650,000 square kilometers) on the Arabian Peninsula, and its name translates to “the Empty Quarter” in English. To unravel the secrets of the desolate terrain, researchers are combining machine learning with a satellite imagery technique that uses radio waves to spot objects that may be concealed beneath surfaces.

    The technology will be tested in October when excavations assess whether predicted structures are present at the Saruq Al Hadid complex in Dubai, United Arab Emirates.

    Separately, an AI-assisted analysis uncovered a trove of ancient symbols in Peru’s Nazca Desert, nearly doubling the number of known geoglyphs, or stone and gravel arranged into giant shapes that depict animals, humans and geometric designs.

  21. Jamestiz表示:

    Как пайщик кооператива «Бест Вей», я не могу молчать о том, что происходит сейчас с нашим кооперативом. Это дело абсолютно сфабриковано с целью разрушить успешную и работающую систему, которая помогает тысячам людей. За эти годы я видел, как многие мои знакомые смогли приобрести квартиры благодаря кооперативу, и теперь всё это пытаются разрушить. Я считаю, что это не что иное, как коррупционная атака на наши активы. Следственные органы фабрикуют обвинения, давят на людей и блокируют счета, чтобы создать иллюзию преступления, которого не было. Я уверен, что кооператив абсолютно чист, и все эти обвинения не выдержат никакой критики. Но пока следствие затягивается, страдают простые пайщики, которые верили в честность и справедливость. Я надеюсь, что правда восторжествует, и все участники этой грязной игры будут разоблачены.

  22. Charlesrab表示:

    trouver un mГ©dicament en pharmacie cialis sans ordonnance pharmacie en ligne avec ordonnance

  23. HeathZex表示:

    pharmacie en ligne avec ordonnance: pharmacie en ligne pas cher – acheter mГ©dicament en ligne sans ordonnance

  24. HeathZex表示:

    Achat mГ©dicament en ligne fiable: cialis sans ordonnance – Pharmacie sans ordonnance

  25. HeathZex表示:

    pharmacie en ligne pas cher: Cialis sans ordonnance 24h – acheter mГ©dicament en ligne sans ordonnance

  26. Профессиональный сервисный центр по ремонту серверов в Москве.
    Мы предлагаем: сколько длится обслуживание сервера
    Наши мастера оперативно устранят неисправности вашего устройства в сервисе или с выездом на дом!

發佈留言

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