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

  1. The very crux of your writing while sounding reasonable initially, did not really settle very well with me personally after some time. Someplace within the paragraphs you actually managed to make me a believer but just for a while. I still have a problem with your jumps in logic and one would do nicely to help fill in all those breaks. If you can accomplish that, I will surely be amazed.

  2. Thanks for your useful post. In recent times, I have been able to understand that the actual symptoms of mesothelioma are caused by the build up of fluid regarding the lining of your lung and the upper body cavity. The infection may start in the chest location and spread to other body parts. Other symptoms of pleural mesothelioma include weight reduction, severe inhaling trouble, a fever, difficulty ingesting, and infection of the face and neck areas. It ought to be noted that some people having the disease do not experience every serious signs and symptoms at all.

  3. nilath表示:

    In accordance with my observation, after a in foreclosure home is marketed at an auction, it is common for your borrower to still have a remaining balance on the bank loan. There are many lenders who aim to have all charges and liens paid off by the upcoming buyer. Nonetheless, depending on particular programs, regulations, and state legislation there may be a few loans which are not easily fixed through the transfer of lending options. Therefore, the duty still falls on the debtor that has acquired his or her property in foreclosure. Many thanks sharing your opinions on this website.

  4. Hello There. I found your blog using msn. This is a very well written article. I?ll be sure to bookmark it and return to read more of your helpful info. Thank you for the post. I?ll definitely return.

  5. DouglasGed表示:

    best online pharmacies in mexico: mexican pharmacy – mexican online pharmacies prescription drugs

  6. DouglasGed表示:

    mexico pharmacies prescription drugs: Medicines Mexico – mexico pharmacies prescription drugs

  7. Thanks for your post. I would like to write my opinion that the expense of car insurance will vary from one insurance policy to another, due to the fact there are so many different facets which give rise to the overall cost. By way of example, the make and model of the motor vehicle will have an enormous bearing on the fee. A reliable ancient family motor vehicle will have a more economical premium than the usual flashy sports car.

  8. DouglasGed表示:

    mexican pharmaceuticals online: purple pharmacy mexico price list – buying prescription drugs in mexico online

  9. I know this if off topic but I’m looking into starting my own blog and was curious 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. Kudos

  10. TerryHax表示:

    Инвестиционная компания HERMES: имитация скама по заданию следствия

    В Санкт-Петербурге, возможно, близится к завершению предварительное расследование уголовного дела о мошенничестве, инициированного ГСУ питерского главка МВД по якобы обнаружившимся фактам мошенничества в работе иностранной инвестиционной компании Hermes. Следствие признало потерпевшими 198 граждан — клиентов Hermes. В числе обвиняемых — Роман Василенко, по версии следствия, один из соучредителей компании.

    Следствие также пытается привлечь к делу кооператив «Бест Вей», заблокировав его деятельность и активы для оплаты обязательств лицам, названным потерпевшими, на том основании, что Василенко являлся руководителем кооператива и другие организации, которые Роман Василенко действительно возглавлял.

    Василенко действительно был председателем правления кооператива до февраля 2021 года, а с февраля 2021 года по март 2022-го — председателем совета кооператива — коллегиального наблюдательного органа, не руководящего операционной деятельностью кооператива в связи с тем, что по семейным обстоятельствам месяцами находился за границей. С весны 2021 года он не занимает никаких должностей в кооперативе.
    Василенко — не соучредитель и не гендиректор Hermes
    При этом наше журналистское расследование выяснило, что учредителем, совладельцем или генеральным директором Hermes Василенко никогда не был: утверждения следствия не соответствуют действительности.

    Hermes — компания полностью иностранная, зарегистрированная в британской юрисдикции. Она начала работать на рынке в 1998 года — гораздо раньше, чем были созданы кооператив «Бест Вей», а также продвиженческий, консультативный и образовательный проекты, организованные Романом Василенко.

    Россиян среди учредителей Hermes нет и не было. Генеральным партнером компании, насколько нам известно, является австрийский инвестор Йохан Риглер. При этом компания активно работала в странах СНГ, имеет десятки тысяч клиентов из России и других стран постсоветского пространства.

    Клиентов привлекало то, что она подчиняется британскому праву и соответствует международным стандартам инвестиционной деятельности. Огромное количество клиентов довольно пассивным доходом, который получало (а после восстановления работы компании и получает) с помощью компании — располагаем сотнями позитивных отзывов, десятки из которых их авторы нам подтвердили лично.

    Hermes сотрудничала с российскими специалистами по продвижению, с Романом Василенко, как с бизнес-коучем. При этом она активно привлекала российских IT-специалистов как лучших в мире. На Hermes работал петербургский IT-специалист Набойченко.

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

    В результате захвата и обрушения сайтов операции по счетам и вывод денег со счетов оказались невозможны — и появились заявления в полицию со стороны клиентов инвесткомпании. Часть из них, по имеющимся у нас данным, была в сговоре со следствием, однако часть поверила в то, что произошел обман и деньги иным способом, кроме как через привлечение к ответственности за мошенничество, не вернуть. При этом большинство клиентов компании из России таких заявлений не подавало, будучи уверенным в том, что кризисная ситуация успешно разрешится.

    Кроме того, с разоблачениями выступил шофер одного из проектов Романа Василенко по фамилии Комаров. Человек, работавший за зарплату 100 тыс. в месяц заявил следствию, что якобы возил неучтенные наличные деньги, хотя в действительно он выполнял мелкие поручения, в частности ездил в аэропорт, забирал пакеты с подарками от пайщиков кооператива подарков, присылаемых из регионов, дал показания (якобы сам), что в пакетах с подарками, находилась неучтенная наличка — хотя признает, что их не вскрывал.

    Липовое уголовное дело
    Вот на этом зыбком основании и искусственном обрушении инфраструктуры Hermes появилось уголовное дело. К этому делу привязали, в том числе, и кооператив «Бест Вей», активы которого следствие стремится использовать для расплаты по обязательствам Hermes, поскольку они находятся в России.

    Это, как сообщили нам юридические эксперты, незаконно, но кооператив пытаются привязать квазизаконными способами, один из которых — как раз утверждение, что ранее руководивший кооперативом Роман Василенко являлся якобы совладельцем Hermes и проекты Романа Василенко и Hermes составляли вместе некий единый холдинг — машину для хищений.

    Кризис преодолен
    На восстановление работы сайтов Hermes и электронных финансовых сервисов IT-специалистами за рубежом понадобилось несколько месяцев. Сейчас, как нам сообщили клиенты компании, сайты и платежные сервисы восстановлены, все счета действуют.

    Более 70% клиентов Hermes уже воспользовалось восстановленными счетами и свободно оперирует своими средствами, в том числе выводят их. Сложная ситуация в работе компании, созданная ее бывшим ключевым сотрудником по наущению оперативных работников полиции, полностью преодолена.

    Преимущество компании Hermes оказалось как раз в том, что она находится за границей и ее деятельность не могут заблокировать российские правоохранительные органы.

    Что же касается кооператива «Бест Вей», то его деятельность пока заблокирована, хотя он прошел бухгалтерскую экспертизу в одном из учреждений Минюста России, которая выяснила, что 81% средств направлялся на покупку квартиры и 19% средств — на организацию деятельности и услуги для кооператива.

    Режиссеры псевдоскама
    Уголовное дело изначально срежиссировано петербургскими оперативниками и следователями Машевским, Сапетовой, Винокуровым и их начальником — главой ГСУ питерского главка МВД генерал-майора юстиции Негрозовым. Цель атаки, возможно, в том, чтобы захватить активы кооператива в интересах группы недобросовестных инвесторов Hermes.

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

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

  11. nattyflix表示:

    Do you have a spam issue on this blog; I also am a blogger, and I was wondering your situation; many of us have created some nice practices and we are looking to swap techniques with others, be sure to shoot me an e-mail if interested.

  12. Fantastic site. A lot of useful info here. I?m sending it to several friends ans also sharing in delicious. And naturally, thanks for your sweat!

  13. you’re really a good webmaster. The site loading speed is incredible. It seems that you’re doing any unique trick. Moreover, The contents are masterpiece. you’ve done a great job on this topic!

  14. hikari sena表示:

    Throughout the grand scheme of things you actually get an A+ with regard to hard work. Exactly where you misplaced us ended up being in all the particulars. As it is said, the devil is in the details… And it could not be much more true at this point. Having said that, permit me inform you what exactly did do the job. The writing is certainly extremely persuasive which is probably why I am making an effort in order to comment. I do not make it a regular habit of doing that. 2nd, even though I can easily notice a jumps in logic you make, I am definitely not certain of just how you seem to connect your details which help to make the final result. For now I will yield to your issue however wish in the foreseeable future you connect the dots much better.

  15. Definitely believe that which you stated. Your favorite justification appeared to be on the net the easiest thing to be aware of. I say to you, I certainly get irked while people consider worries that they just don’t know about. You managed to hit the nail upon the top and defined out the whole thing without having side effect , people can take a signal. Will likely be back to get more. Thanks

  16. DouglasGed表示:

    india pharmacy: Online pharmacy USA – pharmacy website india

  17. I have really learned some new things from the blog post. One other thing to I have found is that usually, FSBO sellers may reject you. Remember, they might prefer to not use your services. But if you maintain a stable, professional partnership, offering support and being in contact for around four to five weeks, you will usually be able to win interviews. From there, a listing follows. Thanks

  18. DouglasGed表示:

    mexico drug stores pharmacies: mexico pharmacy win – mexican drugstore online

  19. It’s the best time to make some plans for the future and it is time to be happy. I’ve read this post and if I could I desire to suggest you some interesting things or tips. Perhaps you can write next articles referring to this article. I want to read even more things about it!

  20. DouglasGed表示:

    pills for erectile dysfunction online: ed pills online – where to get ed pills

  21. Thanks for your short article. I would love to say that a health insurance specialist also utilizes the benefit of the particular coordinators of your group insurance plan. The health broker is given a listing of benefits needed by somebody or a group coordinator. What a broker does is search for individuals or even coordinators which best complement those needs. Then he provides his tips and if the two of you agree, this broker formulates a binding agreement between the two parties.

  22. Have you ever considered writing an ebook or guest authoring on other websites? I have a blog centered on the same ideas you discuss and would really like to have you share some stories/information. I know my readers would enjoy your work. If you’re even remotely interested, feel free to send me an e-mail.

  23. I also believe that mesothelioma cancer is a uncommon form of most cancers that is commonly found in those people previously familiar with asbestos. Cancerous cells form within the mesothelium, which is a shielding lining which covers a lot of the body’s body organs. These cells commonly form while in the lining on the lungs, belly, or the sac which actually encircles one’s heart. Thanks for revealing your ideas.

  24. Lazrdzm表示:

    Привет!
    Мы изготавливаем дипломы психологов, юристов, экономистов и других профессий по приятным тарифам.
    telegra.ph/raschet-stoimosti-obucheniya-v-vuze-08-02

  25. Thanks for the helpful post. It is also my belief that mesothelioma has an very long latency time period, which means that symptoms of the disease may not emerge right up until 30 to 50 years after the initial exposure to asbestos. Pleural mesothelioma, which can be the most common type and has effects on the area within the lungs, could potentially cause shortness of breath, chest muscles pains, along with a persistent coughing, which may lead to coughing up maintain.

  26. hi!,I love your writing very so much! share we keep up a correspondence more approximately your post on AOL? I need a specialist on this area to solve my problem. Maybe that’s you! Having a look forward to look you.

  27. makeyoursday表示:

    The crux of your writing while appearing reasonable at first, did not settle very well with me personally after some time. Someplace within the paragraphs you were able to make me a believer unfortunately only for a short while. I nevertheless have a problem with your jumps in assumptions and you would do well to fill in all those breaks. In the event you can accomplish that, I will certainly end up being impressed.

  28. I do agree with all of the ideas you have introduced for your post. They’re really convincing and will certainly work. Nonetheless, the posts are too quick for novices. May just you please prolong them a little from next time? Thank you for the post.

  29. Mazrkmv表示:

    Добрый день!
    Узнайте, как безопасно купить диплом о высшем образовании
    diplomrushkan.ru

  30. onlyfans表示:

    I believe that avoiding highly processed foods will be the first step to help lose weight. They will often taste fine, but prepared foods possess very little vitamins and minerals, making you try to eat more just to have enough vigor to get over the day. If you are constantly ingesting these foods, transitioning to grain and other complex carbohydrates will assist you to have more vitality while feeding on less. Good blog post.

發佈留言

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