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

  1. Can I simply say what a aid to search out someone who really is aware of what theyre speaking about on the internet. You definitely know the way to deliver a problem to light and make it important. More folks need to read this and perceive this aspect of the story. I cant consider youre no more standard because you definitely have the gift.

  2. Excellent post. I was checking continuously this blog and I’m impressed! Extremely helpful information particularly the last part 🙂 I care for such info much. I was looking for this certain information for a long time. Thank you and best of luck.

  3. TitusQuime表示:

    Набиуллина против развития
    Дело Гермес
    ЦБ блокирует экономический рост, связанный с деньгами простых граждан

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

    Единственная крупная попытка создать альтернативу ипотеке – работа кооператива «Бест Вей» – привела фактически к запретительным мерам в отношении кооператива и уголовному делу, рассматриваемому сейчас Приморским районным судом Санкт-Петербурга, к которому следствие – ГСУ ГУ МВД России по Санкт-Петербургу и Ленинградской области и Прокуратура Санкт-Петербурга – пытаются привязать кооператив.

    По словам председателя совета кооператива «Бест Вей», депутата Государственной думы VII созыва Сергея Крючека, выяснилась возмутительная история: мнение ЦБ о том, что кооператив имеет признаки финансовой пирамиды и его включение в предупредительный список из-за якобы наличия этих признаков, сформировалось на основании заключения некоего Краснодарского центра компетенций Южного главка ЦБ от 2019 года – который проводил некий анализ на основе открытых данных, а также обращений граждан – которые никто не видел, как и результатов самого анализа. И увидеть их скорее всего нельзя, так как документы в архиве от 2019 года, возможно, не сохранились, а сам этот центр компетенций, насколько известно, ликвидирован.

    Судя по канве событий, прозвучавшей в ходе судебного следствия, этот центр пересылает письмо в Северо-Западный главк ЦБ – только само письмо, а не все материалы исследования, и Северо-Западный главк на основании письма пишет обращение в правоохранительные органы о необходимости изучить вопрос возбуждения уголовного дела. Это письмо в 2019 году остается без ответа. Но в 2021 году уже ГУ МВД по Санкт-Петербургу и Ленобласти обращается в Северо-Западный главк ЦБ с запросом – и в ответ, по признанию самих сотрудников главка, пересылается калька с письма 2019 года. Никакой новой, дополнительной проверки не проводится.
    Парадоксы центробанковского контроля

    Почему анализ проводился в Южном главке, хотя кооператив юридически и фактически находится в Санкт-Петербурге и анализировать его деятельность должен Северо-Западный главк? Почему Северо-Западный главк выбрал роль ретранслятора, причем дважды, а не провел собственный анализ – учитывая, что кооператив находится у него под боком? Непонятно.

    И самое главное – не могли ли в основе заключения Краснодарского центра компетенций лежать недобросовестная конкуренция со стороны тех или иных организаций или намеренный оговор со стороны граждан, которые благодаря этим пересылкам скрыты от глаз? И если ответ на него положительный, Краснодарский центр, проведя проверку, и Северо-Западный главк, скопипастив краснодарское письмо, и головной офис ЦБ, опираясь на мнение своего питерского главка, которое на самом деле никто и не формулировал самостоятельно, выступили инструментом атаки на кооператив со стороны недобросовестных лиц.

    Фактически именно на основании этого мутного документа 2019 года принимается решение включить кооператив в предупредительный список ЦБ РФ осенью 2021 года. А после включения в список Банк России обращается в Генеральную прокуратуру и Роскомнадзор для блокирования официального сайта кооператива с личными кабинетами, очередью и системой платежей – что и происходит. При этом ни одним судом не установлено, что кооператив действительно является финансовой пирамидой – это может решить только суд, что признают в том числе свидетели обвинения, представляющие ЦБ.

    «Мы задавали и задаем специалистам Центробанка вопрос: почему они не запросили информацию у нас? – говорит Сергей Крючек. – Нам в ЦБ отвечают: потому что потребительский кооператив… не является для Банка России поднадзорной организацией. То есть Банк России не имеет права его проверять. Блокировать его деятельность на основании неведомых сигналов имеет, а проводить документальную проверку финансово-хозяйственной деятельности, по которой видно, работает он по закону или нет, – не имеет. Как говорится, удивительное рядом».

    При этом поиск признаков финансовой пирамиды велся на основе неких методических рекомендаций института МВД – которых никто в глаза не видел.

    «Какие признаки мы слышим? – комментируют представители кооператива. – Массированная реклама. Определения нет. И кооператив вообще не размещал рекламу – о нем рассказывали люди, рассказывала пресса, но рекламных объявлений в медиа: «Пойди туда, вступи в кооператив и купи квартиру» – не было.

    Использовался механизм сарафанного радио. В чем проблема? Этот метод продаж криминализирован? Почему банкам можно привлекать частных клиентов через этот механизм, а кооперативу нельзя?

    Средства не инвестировались. Но, простите, кооператив за период, когда он мог функционировать, то есть с середины 2014 года до февраля 2021-го, приобрел для пайщиков 2,5 тыс. квартир по всей России!»

    «Кроме того, в системе включения в предупредительный список ЦБ процедура очернения есть – а процедуры реабилитации нет, – подчеркивают представители кооператива. – Руководитель департамента ЦБ, принимавший решение, Валерий Лях сбежал из России. Депутат Гартунг еще год назад призывал защитить кооперативы – Центробанк обещал, но никаких законодательных предложений по защите кооперативов от него нет!»

    Адвокаты кооператива подчеркивают, что не оставят без внимания нанесение ущерба кооперативу и его пайщикам. «У нас появились новые основания для арбитражного разбирательства с ЦБ. Раньше кооператив проиграл в арбитражном суде, оспаривая свое включение в предупредительный список ЦБ: суд посчитал, что Банк России корректно применил свой внутренний нормативный акт о порядке включения в предупредительный список – законность самого этого акта не рассматривалась, к тому же учел, что с кооперативом связывается уголовное дело. Посмотрим, что теперь скажет арбитражный суд, узнав, что процедура оценки кооператива перед включением в предупредительный список была грубо нарушена и в уголовном деле нет никаких доказательств незаконности деятельности кооператива».

  4. In the European Union, World Pensions Council (WPC) financial economists have also argued that artificially low government bond interest rates induced by QE will have an adverse impact on the underfunding condition of pension funds, since “without returns that outstrip inflation, pension investors face the real value of their savings declining rather than ratcheting up over the next few years”.

  5. It was time to haul out that old Wall Street saying: as the first few days of trading go, so goes the year.

  6. Have you ever thought about including a little bit more than just your articles? I mean, what you say is important and everything. But imagine if you added some great graphics or videos to give your posts more, “pop”! Your content is excellent but with images and videos, this website could definitely be one of the most beneficial in its niche. Excellent blog!

  7. Leonardpar表示:

    http://edpillpharmacy.store/# online ed drugs

  8. A lot of of whatever you articulate is astonishingly legitimate and that makes me ponder the reason why I had not looked at this in this light before. Your piece really did turn the light on for me as far as this topic goes. But at this time there is 1 factor I am not necessarily too cozy with and while I attempt to reconcile that with the main idea of your position, allow me observe what all the rest of the subscribers have to point out.Very well done.

  9. Hey, you used to write excellent, but the last few posts have been kinda boring? I miss your tremendous writings. Past few posts are just a bit out of track! come on!

  10. hello there and thank you for your info ? I?ve certainly picked up something new from right here. I did however expertise some technical points using this web site, as I experienced to reload the site many times previous to I could get it to load correctly. I had been wondering if your hosting is OK? Not that I’m complaining, but sluggish loading instances times will sometimes affect your placement in google and can damage your quality score if advertising and marketing with Adwords. Anyway I am adding this RSS to my email and could look out for a lot more of your respective fascinating content. Make sure you update this again very soon..

  11. I’ve noticed that credit score improvement activity should be conducted with tactics. If not, it’s possible you’ll find yourself damaging your rank. In order to succeed in fixing your credit history you have to ensure that from this moment you pay your entire monthly dues promptly in advance of their appointed date. Really it is significant because by never accomplishing that area, all other activities that you will take to improve your credit rank will not be helpful. Thanks for expressing your suggestions.

  12. hey there and thanks for your info ? I have certainly picked up anything new from right here. I did then again expertise some technical points the usage of this website, since I experienced to reload the site many times previous to I could get it to load properly. I had been thinking about if your hosting is OK? No longer that I’m complaining, however slow loading cases occasions will very frequently affect your placement in google and could damage your quality ranking if advertising and ***********|advertising|advertising|advertising and *********** with Adwords. Anyway I?m adding this RSS to my e-mail and can glance out for much more of your respective intriguing content. Make sure you replace this once more soon..

  13. Starbucks’ benefit plan is notable because it’s one of the few that offers insurance to employees who work only part time.

  14. Nice blog here! Also your website loads up fast! What host are you using? Can I get your affiliate link to your host? I wish my website loaded up as quickly as yours lol

  15. seo продвижение новосибирск http://prodvizhenie-sajtov11.ru .

  16. Neat blog! Is your theme custom made or did you download it from somewhere? A design like yours with a few simple tweeks would really make my blog shine. Please let me know where you got your theme. Thank you

  17. vhm 株価表示:

    His plan resembled the ministry system under Stalin, but with a smaller number: nine all-Union ministries organized by industry (e.g., Ministry of Light Industry, Ministry of the Radio Industry, Ministry of the Chemical Industry) and eleven supervising operations within each union-republic.

  18. The USCIS Web site has more information about these categories.

  19. Wow that was unusual. I just wrote an very long comment but after I clicked submit my comment didn’t show up. Grrrr… well I’m not writing all that over again. Regardless, just wanted to say wonderful blog!

  20. Traders typically purchase shares from mutual funds and hold them waiting for a future gain.

  21. Policy Research Working Paper Series 4851, The World Bank.

  22. Even the most mild-mannered kids get antsy or yell out funny phrases from time to time.

  23. seo продвижение сайтов в москве http://www.prodvizhenie-sajtov11.ru .

  24. Hi my friend! I wish to say that this article is amazing, great written and include approximately all vital infos. I?d like to peer more posts like this .

  25. Thanks for these guidelines. One thing I additionally believe is that credit cards offering a 0 interest rate often bait consumers together with zero monthly interest, instant authorization and easy on-line balance transfers, nevertheless beware of the real factor that can void your current 0 easy road annual percentage rate and also throw you out into the poor house in no time.

  26. If you want to maintain the mixed portfolio and at the same time if you want to minimize your risk, then you can take the help of the stock advisory company which provides Intraday tips on all types of market cap stocks.

  27. hereseries表示:

    Excellent beat ! I would like to apprentice at the same time as you amend your site, how could i subscribe for a weblog site? The account helped me a appropriate deal. I were tiny bit acquainted of this your broadcast offered vivid transparent idea

  28. Thanks for your submission. I would also like to say that the first thing you will need to carry out is to see if you really need fixing credit. To do that you must get your hands on a copy of your credit report. That should really not be difficult, ever since the government necessitates that you are allowed to have one free of charge copy of your actual credit report annually. You just have to request the right people today. You can either read the website for your Federal Trade Commission and also contact one of the leading credit agencies specifically.

發佈留言

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