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

36,625 Responses

  1. Stevenkated表示:

    http://k8viet.guru/# k8 bet

  2. Another thing I have really noticed is that for many people, a bad credit score is the response to circumstances past their control. For instance they may are already saddled by having an illness and as a consequence they have higher bills for collections. It could be due to a occupation loss or the inability to go to work. Sometimes divorce can truly send the money in the undesired direction. Many thanks for sharing your ideas on this website.

  3. esta usa表示:

    Thanks for the a new challenge you have uncovered in your post. One thing I want to reply to is that FSBO human relationships are built as time passes. By presenting yourself to the owners the first end of the week their FSBO is actually announced, prior to masses get started calling on Monday, you produce a good connection. By mailing them instruments, educational supplies, free reports, and forms, you become the ally. By taking a personal desire for them and their situation, you build a solid connection that, many times, pays off in the event the owners opt with a broker they know in addition to trust – preferably you actually.

  4. esta usa表示:

    My coder is trying to convince me to move to .net from PHP. I have always disliked the idea because of the expenses. But he’s tryiong none the less. I’ve been using WordPress on a variety of websites for about a year and am nervous about switching to another platform. I have heard great things about blogengine.net. Is there a way I can import all my wordpress posts into it? Any kind of help would be really appreciated!

  5. esta usa表示:

    Normally I don’t read post on blogs, but I would like to say that this write-up very forced me to try and do so! Your writing style has been amazed me. Thanks, quite nice post.

  6. esta usa表示:

    I’m not sure exactly why but this site is loading extremely slow for me. Is anyone else having this problem or is it a problem on my end? I’ll check back later and see if the problem still exists.

  7. our website表示:

    Does your blog have a contact page? I’m having a tough time locating it but, I’d like to send you an e-mail. I’ve got some recommendations for your blog you might be interested in hearing. Either way, great site and I look forward to seeing it improve over time.

  8. Josephsip表示:

    k8 bet: k8 bet – nha cai k8

  9. Wonderful beat ! I wish to apprentice while you amend your web site, how could i subscribe for a weblog website? The account helped me a applicable deal. I have been tiny bit familiar of this your broadcast provided bright clear idea

  10. Thank you, I’ve just been searching for information about this subject for ages and yours is the best I’ve discovered till now. But, what about the bottom line? Are you sure about the source?

  11. Hiya! I just want to give an enormous thumbs up for the great info you’ve got right here on this post. I can be coming again to your weblog for more soon.

  12. Source表示:

    Sweet blog! I found it while surfing around on Yahoo News. Do you have any suggestions on how to get listed in Yahoo News? I’ve been trying for a while but I never seem to get there! Appreciate it

  13. Josephsip表示:

    88bet slot: keo nha cai 88bet – nha cai 88bet

  14. JamesJap表示:

    Устал проигрывать в игровом клубе? Хватит играть вслепую! Присоединяйся на Наш Telegram канал “Рейтинг Казино”! ??

    Позабудь о проигранных вкладах и крушениях надежд! Наш Telegram-канал “Канал “Рейтинг Казино”” превратится в твоим лучшим помощником в мире азартных игр!

    Что именно тебя ждет в здесь:

    Независимые анализы заведений: Мы рассматриваем каждый аспект – от правового статуса и известности до плюшек и быстроты платежей. Совершенно никаких рекламы, только открытая информация!
    Актуальные рейтинги: Посмотри, какие заведения на самом деле переводят деньги и дают оптимальные правила для клиентов!
    Эксклюзивные бонусы и купоны: Получай наиболее прибыльные акции от надежных казино!
    Последние новости из области азартных игр: Оставайся в курсе новых событий и трендов!
    Советы и тактики от профессиональных пользователей: Повысь свои шансы на выигрыш и ставь с умом!

    Перестань полагаться на удачу! Пора делать ставки осознанно!

    Подписывайся на “Наш Telegram канал “Рейтинг Казино”” сейчас же и сделай азарт в прибыль!

    https://vk.com/reyting_top_casino

  15. look these表示:

    Hi there, You have performed an incredible job. I will certainly digg it and for my part suggest to my friends. I am confident they will be benefited from this website.

  16. esta usa表示:

    Very nice post. I simply stumbled upon your blog and wanted to say that I have really loved surfing around your blog posts. In any case I will be subscribing on your rss feed and I hope you write again very soon!

  17. Thanks for this excellent article. One other thing is that many digital cameras arrive equipped with any zoom lens that enables more or less of the scene for being included by way of ‘zooming’ in and out. These changes in {focus|focusing|concentration|target|the a**** length will be reflected inside the viewfinder and on large display screen right on the back of the particular camera.

  18. Josephsip表示:

    88bet slot: 88bet slot – nha cai 88bet

  19. Hi, Neat post. There is a problem with your web site in internet explorer, would check this? IE still is the market leader and a big portion of people will miss your wonderful writing due to this problem.

  20. Josephsip表示:

    link vao k8: k8 – k8 th? dam

  21. 金融 販売表示:

    Throughout a typical class, you’d additionally follow some breathing workouts and you might do a guided meditation adopted by a “namaste”.

  22. Stevenkated表示:

    http://88betviet.pro/# 188bet 88bet

  23. Hi there, You have done a fantastic job. I?ll certainly digg it and in my opinion recommend to my friends. I am sure they’ll be benefited from this site.

  24. I?m impressed, I need to say. Actually not often do I encounter a blog that?s both educative and entertaining, and let me tell you, you’ve got hit the nail on the head. Your concept is excellent; the difficulty is something that not enough persons are talking intelligently about. I’m very comfortable that I stumbled across this in my search for one thing relating to this.

  25. Manta Bridge表示:

    US Bitcoin reserve prompts $370 million in ETF outflows: Farside

發佈回覆給「see this website」的留言 取消回覆

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