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

11,192 Responses

  1. I?ll immediately grab your rss as I can’t find your email subscription link or e-newsletter service. Do you’ve any? Kindly let me know in order that I could subscribe. Thanks.

  2. Would you be fascinated by exchanging hyperlinks?

  3. Hello there! This is my 1st comment here so I just wanted to give a quick shout out and say I really enjoy reading your posts. Can you suggest any other blogs/websites/forums that deal with the same topics? Thanks!

  4. poker online表示:

    Feel free to visit my page :: poker online

  5. JamesJus表示:

    Как обратиться к нам за юридической консультацией?
    бесплатная консультация по телефону юрист
    Чтобы получить юридическую консультацию, с нами можно связаться онлайн или же по телефону. Мы подберём вам юриста, специализирующегося именно в той сфере законодательства, с которой связаны ваши проблемы. Это поможет быстро достичь нужного результата и, безусловно, будет лучшим выбором, если вам нужно незамедлительно получить юридические услуги.

    Бесплатная юридическая консультация по телефону может стать вашим спасением. Предоставленная нами консультация поможет вам сориентироваться в вопросе и решить, нужна ли вам дальнейшая помощь, которую может обеспечить Коллегия адвокатов № 1. После того как юридическая консультация по телефону будет проведена и проблемы будут чётко обозначены, наши юристы могут оказать вам и дальнейшие услуги — от оформления нужных документов до представления ваших интересов в зале суда.

  6. Hi, Neat post. There is a problem with your site in internet explorer, would test this? IE still is the market leader and a large portion of people will miss your magnificent writing due to this problem.

  7. I know this if off topic but I’m looking into starting my own weblog and was wondering what all is required to get set up? I’m assuming having a blog like yours would cost a pretty penny? I’m not very web savvy so I’m not 100 positive. Any tips or advice would be greatly appreciated. Thanks

  8. I absolutely love your blog and find most of your post’s to be precisely what I’m looking for. can you offer guest writers to write content in your case? I wouldn’t mind composing a post or elaborating on a few of the subjects you write concerning here. Again, awesome web site!

  9. Great goods from you, man. I’ve understand your stuff previous to and you’re just extremely fantastic. I actually like what you have acquired here, really like what you are saying and the way in which you say it. You make it enjoyable and you still care for to keep it smart. I can’t wait to read far more from you. This is really a great site.

  10. Nice weblog here! Also your web site lots up very fast! What host are you the usage of? Can I am getting your affiliate link on your host? I want my website loaded up as quickly as yours lol

  11. I have discovered some points through your blog post post. One other point I would like to express is that there are plenty of games on the market designed especially for preschool age kids. They contain pattern acceptance, colors, creatures, and styles. These normally focus on familiarization rather than memorization. This helps to keep children occupied without feeling like they are learning. Thanks

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

  13. MathewCluth表示:

    Elon Musk’s X just sued a nonprofit advertising group out of existence
    сколько стоит адвокат по разделу имущества
    A major ad industry group is shutting down, days after Elon Musk-owned X filed a lawsuit that claimed the group illegally conspired to boycott advertising on his platform.

    “GARM is a small, not-for-profit initiative, and recent allegations that unfortunately misconstrue its purpose and activities have caused a distraction and significantly drained its resources and finances,” the group said in a statement Friday. “GARM therefore is making the difficult decision to discontinue its activities.”

    The group, Global Alliance for Responsible Media, also known as GARM, is a voluntary ad-industry initiative run by the World Federation of Advertisers that aims to help brands avoid having their advertisements appear alongside illegal or harmful content. GARM confirmed it is still planning to defend itself in court.

    The end of GARM marks a temporary victory for Musk and X CEO Linda Yaccarino, even though a judge hasn’t made a ruling yet.

    “No small group should be able to monopolize what gets monetized. This is an important acknowledgement and a necessary step in the right direction. I am hopeful that it means ecosystem-wide reform is coming,” Yaccarino posted on X Thursday.

    However, the lawsuit could drive away even more advertisers from X, Nandini Jammi and Claire Atkin, founders of watchdog group Check My Ads Institute wrote in an op-ed Thursday. “Everyone can see that advertising on X is a treacherous business relationship for advertisers,” they said.

  14. I’ve come across that these days, more and more people will be attracted to cameras and the issue of pictures. However, to be a photographer, you must first expend so much time period deciding the model of digital camera to buy and also moving store to store just so you may buy the cheapest camera of the brand you have decided to pick out. But it would not end at this time there. You also have to take into account whether you can purchase a digital digicam extended warranty. Many thanks for the good guidelines I obtained from your blog site.

  15. PatrickBoads表示:

    Как формировался рейтинг организаций, представляющих юридические услуги в Москве
    1 5 2001
    Непросто найти хорошего специалиста, когда появляются проблемы правового характера. Особенно если нужна экстренная помощь, а среди знакомых никто не может порекомендовать квалифицированного адвоката. Для тех, кому срочно требуются юридические услуги, мы сформировали рейтинг организаций Москвы, которые успешно работают долгие годы. Адвокаты представленных фирм помогли тысячам своих доверителей отстоять права в досудебном и судебном порядке. Имеющиеся обширные знания в области юриспруденции и наработанный опыт позволяют им занимать лидирующие позиции на рынке. Зайдя на наш сайт юридических услуг, вы можете познакомиться с ними поближе и выбрать подходящих правозащитников.

    При формировании рейтинга учитывались следующие показатели:

    Опыт работы в сфере юриспруденции;
    Приемлемая оплата услуг юриста;
    Квалификация сотрудников, успешность судебной практики;
    Наличие бесплатных консультаций, оперативность работы.
    Чтобы заказать юридические услуги в проверенной и надежной организации, воспользуйтесь данными нашего рейтинга. Обратившись в фирмы из представленного списка, вы сможете успешно разрешить возникшую проблему в свою пользу.

  16. Thank you sharing these types of wonderful posts. In addition, the optimal travel plus medical insurance program can often relieve those worries that come with vacationing abroad. A medical emergency can in the near future become expensive and that’s absolute to quickly set a financial burden on the family’s finances. Having in place the perfect travel insurance program prior to leaving is well worth the time and effort. Thanks a lot

  17. I believe this is among the such a lot significant info for me. And i am satisfied reading your article. However want to remark on some normal things, The site taste is perfect, the articles is really great : D. Good job, cheers

  18. Hey there! Do you know if they make any plugins to protect against hackers? I’m kinda paranoid about losing everything I’ve worked hard on. Any suggestions?

  19. тревожная кнопка вневедомственной охраны стоимость тревожная кнопка вневедомственной охраны стоимость .

  20. I savour, lead to I found exactly what I used to be having a look for. You’ve ended my 4 day long hunt! God Bless you man. Have a nice day. Bye

  21. Thanks for your article. It’s very unfortunate that over the last years, the travel industry has already been able to to tackle terrorism, SARS, tsunamis, bird flu, swine flu, plus the first ever true global tough economy. Through everthing the industry has proven to be effective, resilient and dynamic, getting new methods to deal with trouble. There are constantly fresh issues and opportunity to which the business must again adapt and reply.

  22. Wonderful work! This is the type of info that should be shared around the internet. Shame on Google for not positioning this post higher! Come on over and visit my web site . Thanks =)

  23. whoah this blog is fantastic i love reading your posts. Stay up the great paintings! You already know, a lot of individuals are hunting around for this info, you could aid them greatly.

  24. Nice post. I used to be checking continuously this blog and I am impressed! Extremely useful information particularly the final part 🙂 I maintain such info much. I used to be seeking this particular info for a very lengthy time. Thank you and best of luck.

  25. электрокарниз москва электрокарниз москва .

  26. Wow, this article is mind-blowing! The author has done a fantastic job of delivering the information in an compelling and informative manner. I can’t thank her enough for sharing such precious insights that have undoubtedly enhanced my understanding in this subject area. Kudos to her for producing such a gem!

  27. plintus_msMn表示:

    Лучшие виды плинтусов для отделки пола, для завершения ремонта|Практичные рекомендации по выбору плинтуса для пола, для создания уютной обстановки|Полезные советы по монтажу плинтусов для пола, для качественного результата|Лучшие способы покраски напольных плинтусов, который подчеркнет уникальность вашего интерьера|Выбор между деревянным, пластиковым и металлическим плинтусом, для обеспечения долговечности|Топ-10 дизайнерских идей использования плинтусов в интерьере, для придания уникального шарма|Почему плинтусы являются важной частью дизайна интерьера, чтобы понять их ценность|Советы по чистке и обслуживанию плинтусов, для продления срока службы плинтусов|Как выбрать безопасные и гипоаллергенные плинтусы для детей, которые сделают детскую комнату уютной и безопасной|Идеи для сочетания цветов плинтуса с отделкой пола, для создания атмосферы уюта и гармонии|Как использовать плинтусы для маскировки дефектов и неровностей, для создания иллюзии идеального покрытия|Как создать эффектный контраст с помощью плинтусов, которые добавят оригинальности и смелости в оформление|Идеи для гармоничного сочетания плинтусов с низкими потолками, которые помогут создать простор и легкость в интерьере|Как оформить углы с помощью плинтусов без видимых швов, для создания аккуратных и эстетичных деталей|Советы по выбору влагостойких и долговечных плинтусов для ванных комнат, для обеспечения защиты от влаги и формирования плесени|Советы по выбору плинтусов
    купить плинтус широкий купить плинтус широкий .

  28. My developer is trying to convince me to move to .net from PHP. I have always disliked the idea because of the costs. But he’s tryiong none the less. I’ve been using WordPress on various websites for about a year and am worried about switching to another platform. I have heard good 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!

  29. Отличный сайт! Всем рекомендую!Лечение наркомании

發佈留言

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