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

  1. Edwarddig表示:

    pin-up 141 casino: pin-up 141 casino – ?Onlayn Kazino

  2. cbd massage表示:

    I do agree with all the ideas you have presented in your post. They are really convincing and will certainly work. Still, the posts are very short for novices. Could you please extend them a bit from next time? Thanks for the post.

  3. Edwarddig表示:

    Pin Up: pin-up 141 casino – Pin Up Azerbaycan

  4. Today, taking into consideration the fast way of living that everyone is having, credit cards have a huge demand in the economy. Persons coming from every area of life are using the credit card and people who not using the credit cards have made arrangements to apply for 1. Thanks for sharing your ideas in credit cards.

  5. hey there and thank you for your information ? I?ve definitely picked up anything new from right here. I did however expertise several technical points using this website, since I experienced to reload the website lots of times previous to I could get it to load correctly. I had been wondering if your web hosting is OK? Not that I am complaining, but sluggish loading instances times will sometimes affect your placement in google and could damage your high-quality score if ads and marketing with Adwords. Well I?m adding this RSS to my e-mail and can look out for much more of your respective intriguing content. Ensure that you update this again very soon..

  6. One important issue is that when you are searching for a student loan you may find that you’ll want a co-signer. There are many conditions where this is correct because you might discover that you do not employ a past credit standing so the loan provider will require that you’ve got someone cosign the loan for you. Great post.

  7. A different issue is really that video gaming became one of the all-time largest forms of fun for people of any age. Kids have fun with video games, and also adults do, too. The XBox 360 is probably the favorite games systems for those who love to have a lot of activities available to them, as well as who like to relax and play live with other folks all over the world. Thank you for sharing your thinking.

  8. bokep jilbab表示:

    hello!,I love your writing so much! percentage we communicate extra about your post on AOL? I need an expert on this area to resolve my problem. May be that is you! Taking a look forward to peer you.

  9. Would you be concerned about exchanging hyperlinks?

  10. I have realized that in unwanted cameras, special sensors help to {focus|concentrate|maintain focus|target|a**** automatically. Those sensors involving some video cameras change in in the area of contrast, while others use a beam involving infra-red (IR) light, especially in low lighting. Higher standards cameras occasionally use a mix of both methods and might have Face Priority AF where the photographic camera can ‘See’ any face while keeping your focus only on that. Many thanks for sharing your ideas on this site.

  11. Thank you for every other informative site. Where else may I get that type of information written in such an ideal means? I’ve a undertaking that I am simply now working on, and I have been at the look out for such info.

  12. Have you ever considered creating an ebook or guest authoring on other websites? I have a blog centered on the same topics you discuss and would love to have you share some stories/information. I know my readers would enjoy your work. If you are even remotely interested, feel free to send me an email.

  13. cbd massage表示:

    Thank you for this article. I will also like to say that it can be hard when you find yourself in school and starting out to establish a long credit ranking. There are many learners who are just simply trying to make it through and have long or favourable credit history are often a difficult issue to have.

  14. Edwarddig表示:

    pin-up kazino: Pin Up Azerbaycan ?Onlayn Kazino – Pin-up Giris

  15. Many thanks for this article. I would also like to mention that it can be hard when you find yourself in school and starting out to initiate a long credit score. There are many college students who are simply just trying to endure and have an extended or positive credit history can occasionally be a difficult matter to have.

  16. Edwarddig表示:

    pin-up360: pin-up kazino – ?Onlayn Kazino

  17. cbd massage表示:

    After examine a few of the weblog posts in your web site now, and I really like your approach of blogging. I bookmarked it to my bookmark web site checklist and can be checking back soon. Pls try my web site as nicely and let me know what you think.

  18. whoah this blog is great i love reading your articles. Keep up the great work! You know, lots of people are looking around for this info, you can help them greatly.

發佈留言

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