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

16,475 Responses

  1. StevenNub表示:

    amoxicillin 500: amoxil – amoxicillin over the counter in canada

  2. porn movie表示:

    I have witnessed that fees for on-line degree experts tend to be an awesome value. Like a full Bachelor’s Degree in Communication in the University of Phoenix Online consists of Sixty credits at $515/credit or $30,900. Also American Intercontinental University Online provides a Bachelors of Business Administration with a entire course requirement of 180 units and a tuition fee of $30,560. Online degree learning has made having your certification far more easy because you can certainly earn your current degree from the comfort in your home and when you finish from office. Thanks for all the other tips I’ve learned through the blog.

  3. One more thing. I really believe that there are many travel insurance sites of respected companies than enable you to enter your journey details and find you the quotations. You can also purchase an international travel insurance policy on the net by using the credit card. All you need to do should be to enter your own travel details and you can begin to see the plans side-by-side. Just find the plan that suits your financial allowance and needs and after that use your credit card to buy the idea. Travel insurance online is a good way to take a look for a trustworthy company pertaining to international travel insurance. Thanks for expressing your ideas.

  4. porn movie表示:

    I?ll immediately seize your rss feed as I can not to find your email subscription link or newsletter service. Do you’ve any? Kindly permit me realize in order that I may subscribe. Thanks.

  5. We are a bunch of volunteers and opening a brand new scheme in our community. Your site provided us with helpful information to paintings on. You have done an impressive activity and our whole community can be grateful to you.

  6. Thanks for the various tips discussed on this site. I have observed that many insurance agencies offer prospects generous savings if they choose to insure a couple of cars with them. A significant variety of households own several cars or trucks these days, especially those with old teenage kids still residing at home, and the savings in policies can easily soon increase. So it is a good idea to look for a great deal.

  7. I love your blog.. very nice colors & theme. Did you design this website yourself or did you hire someone to do it for you? Plz reply as I’m looking to construct my own blog and would like to know where u got this from. kudos

  8. Thank you for some other magnificent post. The place else may just anyone get that type of info in such a perfect approach of writing? I have a presentation subsequent week, and I’m on the search for such info.

  9. Lazriei表示:

    Официальная покупка диплома вуза с сокращенной программой в Москве
    sampnl.listbb.ru/viewtopic.php?f=3&t=837

  10. gay sex表示:

    When I initially commented I clicked the “Notify me when new comments are added” checkbox and now each time a comment is added I get several emails with the same comment. Is there any way you can remove me from that service? Many thanks!

  11. Explore Mostbet Bangladesh for great gaming experiences | Bet on your favorite sports with Mostbet in Bangladesh | Play Aviator and win rewards on Mostbet | Explore Mostbet’s diverse casino game selection | Mostbet’s Aviator game is a favorite among players | Bet anytime, anywhere with Mostbet app download | Experience innovative features on Mostbet app https://www.mostbetbangladeshbd.com.

  12. StevenNub表示:

    can i buy amoxicillin over the counter: Com Pharm – amoxicillin 500mg capsules antibiotic

  13. gay sex表示:

    I have noticed that in digital camera models, special receptors help to {focus|concentrate|maintain focus|target|a**** automatically. The particular sensors connected with some camcorders change in in the area of contrast, while others start using a beam with infra-red (IR) light, especially in low lumination. Higher standards cameras sometimes use a blend of both methods and could have Face Priority AF where the camera can ‘See’ any face while focusing only on that. Many thanks for sharing your notions on this web site.

  14. porn movie表示:

    My programmer is trying to persuade 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 number of websites for about a year and am concerned about switching to another platform. I have heard great things about blogengine.net. Is there a way I can transfer all my wordpress content into it? Any help would be greatly appreciated!

  15. BrandenSlomy表示:

    generic amoxicillin: buy amoxil online – amoxicillin 500mg cost

發佈留言

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