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

10,431 Responses

  1. Heya! I’m at work surfing around your blog from my new iphone! Just wanted to say I love reading your blog and look forward to all your posts! Keep up the fantastic work!

  2. Pretty portion of content. I simply stumbled upon your blog and in accession capital to assert that I get in fact loved account your blog posts. Any way I?ll be subscribing for your feeds or even I success you access constantly quickly.

  3. A lot of whatever you say happens to be supprisingly appropriate and that makes me ponder why I hadn’t looked at this in this light previously. This particular article truly did switch the light on for me as far as this particular issue goes. However at this time there is one particular factor I am not necessarily too comfortable with and while I attempt to reconcile that with the actual core theme of your point, permit me see exactly what the rest of your readers have to point out.Nicely done.

  4. hi!,I like your writing very much! share we communicate more about your post on AOL? I need an expert on this area to solve my problem. May be that’s you! Looking forward to see you.

  5. Can I simply say what a reduction to search out someone who truly is aware of what theyre talking about on the internet. You definitely know how to bring an issue to gentle and make it important. Extra people need to read this and perceive this facet of the story. I cant believe youre no more fashionable since you definitely have the gift.

  6. ไทยxxx表示:

    I have come across that now, more and more people will be attracted to digital cameras and the area of photography. However, really being a photographer, it’s important to first commit so much time frame deciding the model of camera to buy in addition to moving from store to store just so you can buy the least expensive camera of the trademark you have decided to pick. But it isn’t going to end there. You also have to take into account whether you should buy a digital photographic camera extended warranty. Thx for the good guidelines I gathered from your site.

  7. Hello there, You’ve done an excellent job. I?ll definitely digg it and personally suggest to my friends. I’m confident they’ll be benefited from this website.

  8. Thanks for your helpful article. One other problem is that mesothelioma is generally brought on by the inhalation of dust from asbestos, which is a positivelly dangerous material. It is commonly viewed among staff in the construction industry who’ve long experience of asbestos. It could be caused by moving into asbestos insulated buildings for years of time, Family genes plays an important role, and some people are more vulnerable on the risk as compared to others.

  9. Hmm it seems like your blog ate my first comment (it was extremely long) so I guess I’ll just sum it up what I wrote and say, I’m thoroughly enjoying your blog. I too am an aspiring blog writer but I’m still new to everything. Do you have any tips for rookie blog writers? I’d really appreciate it.

  10. I was very pleased to seek out this internet-site.I wished to thanks for your time for this glorious learn!! I definitely enjoying every little little bit of it and I’ve you bookmarked to take a look at new stuff you blog post.

  11. Cazrvux表示:

    Здравствуйте!
    Заказать диплом о высшем образовании
    skippingstonesrocks.com/stick-concept-homework/#comment-33988

  12. Samuelalusy表示:

    Меня просто разрывает от несправедливости! Как такое вообще возможно? Я пришел в “Бест Вей“, потому что верил в этот кооператив, в его идеи, в его честность. Я доверял свои деньги людям, которые никогда не давали повода сомневаться в их порядочности! А теперь что? Всё разрушено из-за каких-то бумажек из Краснодара, которые даже не могут найти? Где эти документы? Где доказательства? Они просто уничтожили всё, во что я верил! Арестовали счета, и теперь у нас задолженности. Почему? Потому что кто-то решил, что мы – пирамида! Да это просто смех, если бы не было так больно! Нам, пайщикам, которые вложили свои деньги и верили в лучшее будущее, просто перекрыли кислород. Адвокаты говорят о каких-то процессуальных нарушениях… Так пусть эти виновные сидят на скамье подсудимых, а не те, кто действительно работал для нас! Я хочу, чтобы справедливость восторжествовала, чтобы виновные понесли наказание!

  13. Gofxoq表示:

    mebeverine generic – cilostazol 100 mg oral buy cilostazol 100 mg generic

  14. Отличный сайт! Всем рекомендую!проститутки СПб

  15. Printyhu9nep表示:

    Convert BTC to PayPal with ease and enjoy quick access to your funds.

  16. Hlkinn10Gip表示:

    Convert your Bitcoin to PayPal quickly and securely with our trusted exchange service.

  17. заказать машину для переезда заказать машину для переезда .

  18. Cazrvga表示:

    Как правильно купить диплом колледжа и ВУЗа в России, подводные камни

    ulfishing.ru/includes/kls/gde_kupit_diplom_instituta_bez_problem_i_lishnih_voprosov_1

  19. silovye_wzSn表示:

    Топовые силовые тренажеры Impulse Fitness, для здоровья и красоты.
    Захватывающие силовые тренажеры Impulse Fitness, с высокой производительностью и комфортом.
    Как выбрать лучшие силовые тренажеры Impulse Fitness, и сэкономить время и деньги.
    Тренируйтесь с удовольствием: лучшие силовые тренажеры Impulse Fitness, и поднять настроение.
    Новейшие силовые тренажеры Impulse Fitness, которые делают занятия спортом более эффективными.
    Тренировка с умом: выбор силовых тренажеров Impulse Fitness, для спортсменов-профессионалов.
    Новейшие технологии в тренировках: тренажеры Impulse Fitness, для требовательных спортсменов.
    Эффективные тренировки с тренажерами Impulse Fitness, которые станут вашим надежным партнером.
    Преимущества тренировок с тренажерами Impulse Fitness, для оптимальных результатов.
    Идеальные силовые тренажеры Impulse Fitness для домашнего зала, для удобных тренировок дома.
    тренажеры силовые для дома тренажеры силовые для дома .

發佈留言

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