Monday, October 21, 2013

Date Diff and Date Add

Finding the number  of years, months, days, minutes, seconds, or milliseconds between two date times can be a hard task for beginners. In this post, you will learn how to calculate the difference in days between two date times and to calculate the future and past dates from the current date. These tasks can be done simply by using the Joda-Time library. It is the most useful library to work with date and times. You will need to download this library from Joda-Time website. You will get a zip file. Please extract the zip file to a folder that you can file.

To use the Joda-Time library in your code, you need to add the jar file (joda-time-2.2.jar) to the build path of the Eclipse. You can follow the step below to add the library to the project in Eclipse.
1. From the Project menu, select Properties.
2. On the properties window, select Java Build Path. Then select Add External Jars...

Add library to Eclipse build path


3. Browse to find the jar file that you have extracted. Then click OK.

If you are using the Windows' command prompt to compile and run your java program, you will need to the add the path of the jar file to the CLASSPATH by going to the Control Panel->System->Advanced System Settings. In the System Properties dialog, select Environment Variables. In the box under User variables, double-click CLASSPATH. Then append the path of the jar file to the Variable value text box. You will use the semi-colon (;) to separate each path entry.

Now you are ready to use the Jodatime library. To calculate the difference between two date times, you can use the Years.Years.yearsBetween, Months.monthsBetween, Days.daysBetween, Hours.hoursBetween, Minutes.minutesBetween, Seconds.secondsBetween methods. The example code below calculates the days and hours between the current and another future date.

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import org.joda.time.DateTime;
import org.joda.time.Days;
import org.joda.time.Hours;

public class DateDiff {
public static void main(String[] args){
DateFormat formatter = new SimpleDateFormat("dd-MM-yyyyy");

Date futureDate=null;
Date today = Calendar.getInstance().getTime();

try{
futureDate= formatter.parse("30-10-2013");
}
catch(ParseException pe)    {
   System.out.println("Parser Exception");
}

Days days = Days.daysBetween(new DateTime(today),new DateTime(futureDate));
Hours hours=Hours.hoursBetween(new DateTime(today), new DateTime(futureDate));
System.out.println(" Days Between " + today + " and " + futureDate + " :" + days.getDays());
System.out.println(" Hours Between " + today + " and " + futureDate + " :" + hours.getHours());


}
}


If you would like to calculate the future date by adding a number of years, months, days, hours, minutes, seconds, or milliseconds to the current date, you will use the plusYears, plusMonths, plusDays, plusHours, plusMinutes, plusSeconds, or plusMillis methods of the DateTime class. Similarly, to find the past date, you can use the minusYears, minusMonths, minusDays, minusHours, minusMinutes, minusSeconds, or minusMillis methods. Read the example code below.


import java.util.Calendar;
import java.util.Date;
import org.joda.time.DateTime;

public class DateAdd{
public static void main(String[] args){
Date today = Calendar.getInstance().getTime();
DateTime dt=new DateTime(today);
DateTime futureDate=dt.plusDays(2); //add two days to the current date
System.out.println("The future date is "+futureDate);


}
}


 
compass app flashLight app

97 comments:

  1. Information about JAVA have spread all over the world wide web, but this information is quite unique and attractive. Thanks for sharing it in here. Keep blogging

    JAVA Training in Chennai
    JAVA Training Chennai

    ReplyDelete
  2. Pretty Post! Vital piece of information, I had come to know about your web- from my friend Andria, Chennai I have read nearly seven posts of yours by now, and let me tell you, your post gives the useful and the most interesting information. This is just the kind of information that I had been looking for, I’m already your RSS reader now and I feel happy about it and I love learning more about this topic.
    Regards,
    ccna course in Chennai|ccna training in Chennai|ccna training institute in Chennai

    ReplyDelete
  3. Good Post! Thank you so much for sharing this pretty post, it was so good to read and useful to improve my knowledge as updated one, keep blogging…
    Regards,
    Python Training in Chennai|Angularjs training in chennai|Angular institutes in Chennai


    ReplyDelete
  4. awesome post about learning center,which is useful and valuable information to share with others.it was an most helpful library to know about java programming codes.
    JAVA Training in Chennai

    ReplyDelete
  5. it was really good to know about these things , unique information and interesting too.

    selenium training in chennai





    ReplyDelete
  6. Excellent write-up as well as excellent site, I enjoy these types of demanding content hold this unique somebody.App Buzz

    ReplyDelete
  7. The strategy you have posted on this technology helped me to get into the next level and had lot of information in it. The Struts, Spring, Hibernate are the advanced level of programming language which are most widely used.
    struts training in chennai | struts training

    ReplyDelete
  8. Excellent post. Thanks for sharing such a useful post.

    web design training in chennai

    ReplyDelete
  9. • such a good website and given to more information thanks! and more visit...
    JAVA TESTING TRAINING IN CHENNAI

    ReplyDelete
  10. Helpful post.Thanks for taking to share this.In a future everything is going to be automatic, connected and digital, embedded system engineer’s duty will be immense. An embedded system has great scope in future. Embedded Training in Chennai may get you placed in the good company.
    Regards,
    Embedded course in Chennai | AWS Training Institutes in Chennai | AWS Training center in Chennai

    ReplyDelete
  11. This data is great and amazing. A debt of gratitude is in order for taking an ideal opportunity to talk about this, I feel upbeat about it and I adore adapting more about this theme. I utilize your manual for teach my understudies.
    Thanks,
    Selenium Training institute in Chennai | Selenium Training in Chennai | Selenium Training

    ReplyDelete
  12. Wonderful Post. With one of a kind substance, I truly motivate enthusiasm to peruse this post. I trust this article help huge numbers of them who looking this pretty data.
    Regards,
    Java Training in Chennai | Java courses in Chennai | J2EE Training in Chennai

    ReplyDelete
  13. Im no expert, but I believe you just made an excellent You certainly understand what youre speaking about, and I can truly get behind that.
    Best JAVA Training institute in Chennai|Java Courses in Chennai

    ReplyDelete
  14. Awesome post, I would definitely say that you have explained it very well with practical scenarios. please keep sharing such articles.

    Selenium training in Chennai | Best Selenium training institute in Chennai
    Thanks a lot.

    ReplyDelete
  15. Thanks for your informative article on Blogger. I think of creating my new website using blogger.
    PHP Training in Chennai

    ReplyDelete
  16. Thanks for sharing informative articl. Your article helped me a lot to understand the concepts well. Salesforce Training in Chennai | Salesforce Training Institutes in Chennai

    ReplyDelete
  17. Thanks for your informative blog!!! Your article helped me to understand the future of. Keep on updating your with such awesome information.Thank you so much for sharing tis worth able content with us. The concept taken here will be useful for my future programs . Keep blogging article like this.

    softwaretesting Training in chennai

    ReplyDelete

  18. I have been reading your blog posts. You blog posts are awesome. They provide good and extremely information which is more valuable. Selenium Training in Chennai is predominant famous for Selenium Automation Training and how to get the necessary knowledge about the technology and implement it in a effective way.

    ReplyDelete
  19. This topic has always been one of my favorite subjects to read about. I have found your post to be very rousing and full of good information. I will check your other articles shortly.
    limo service va

    ReplyDelete
  20. Good one, very informative.. thanks for sharing your views and ideas.. it is very useful to me.. thanks once again.

    Dot Net Training in chennai |
    Dot Net Training institute in chennai

    ReplyDelete
  21. Thanks a lot! You made a new blog entry to answer my question; I really appreciate your time and effort.
    core java training in chennai |
    Top 10 java training institute in chennai

    ReplyDelete
  22. Good and nice blog post, thanks for sharing your information.. it is very useful to me.. keep rocks and updating.

    Java Training in chennai

    ReplyDelete
  23. Thanks for sharing informative article. Download Windows 7 ultimate for free from getintopc. It helps you to explore full functionality of windows operating system.

    ReplyDelete
  24. Your good knowledge and kindness in playing with all the pieces were very useful. I don’t know what I would have done if I had not encountered such a step like this.


    http://www.trainingbangalore.in/big-data-analytics-training-in-bangalore.html

    ReplyDelete
  25. It is very useful information. It will help to improve my knowledge in Selenium. Thank you for sharing this awesome site.
    Selenium Training in Chennai | Selenium Training | Selenium Course in Chennai | Selenium Training Institute in Chennai

    ReplyDelete
  26. I am really enjoying reading your well written articles.
    It looks like you spend a lot of effort and time on your blog.
    I have bookmarked it and I am looking forward to reading new articles. Keep up the good work..
    hadoop institute in bangalore
    best institute for bigdata in bangalore
    big data coaching in bangalore
    Core Java Training in Bangalore
    Best Java Training in Bangalore
    Advanced Java Training in Bangalore

    ReplyDelete
  27. Informative post,It is useful for me to clear my doubts.I hope others also like the information you gave in your blog.
    AWS Training in Vadapalani
    AWS Training in Mogappair
    AWS Training in Bangalore
    AWS Training

    ReplyDelete
  28. Thank you for excellent article.

    Please refer below if you are looking for best project center in

    coimbatore

    http://www.trainingincoimbatore.in/final-year-projects-in-

    coimbatore.html
    http://www.trainingincoimbatore.in/final-year-projects-for-cse-in-

    coimbatore.html
    http://www.trainingincoimbatore.in/final-year-projects-for-it-in-

    coimbatore.html
    http://www.trainingincoimbatore.in/final-year-projects-for-ece-in-

    coimbatore.html
    http://www.trainingincoimbatore.in/final-year-projects-for-eee-in-

    coimbatore.html
    http://www.trainingincoimbatore.in/final-year-projects-for-

    mechanical-in-coimbatore.html
    http://www.trainingincoimbatore.in/final-projects-for-

    instrumentation-in-coimbatore.html

    ReplyDelete
  29. Thank you for excellent article.

    Please refer below if you are looking for best project center in

    coimbatore

    http://www.trainingincoimbatore.in/final-year-projects-in-coimbatore.html
    http://www.trainingincoimbatore.in/final-year-projects-for-cse-in-coimbatore.html
    http://www.trainingincoimbatore.in/final-year-projects-for-it-in-coimbatore.html
    http://www.trainingincoimbatore.in/final-year-projects-for-ece-in-coimbatore.html
    http://www.trainingincoimbatore.in/final-year-projects-for-eee-in-coimbatore.html
    http://www.trainingincoimbatore.in/final-year-projects-for-mechanical-in-coimbatore.html
    http://www.trainingincoimbatore.in/final-projects-for-instrumentation-in-coimbatore.html

    ReplyDelete
  30. Very Good Blog. Highly valuable information have been shared. Highly useful blog..Great information has been shared. We expect many more blogs from the author. Special thanks for sharing..
    SAP Training in Chennai | AWS Training in Chennai | Android Training in Chennai | Selenium Training in Chennai | Networking Training in Chennai

    ReplyDelete
  31. This comment has been removed by the author.

    ReplyDelete
  32. Very nice, it’s really amazing and informative also. Visit OGEN Infosystem for Best Website Designing Company and get creative and responsive website designing.
    Best Website Designing Company in Delhi

    ReplyDelete
  33. It is really a very informative post for all those budding entreprenuers planning to take advantage of post for business expansions. You always share such a wonderful articlewhich helps us to gain knowledge .Thanks for sharing such a wonderful article, It will be deinitely helpful and fruitful article.
    Cyber Security Training Course in Chennai | Certification | Cyber Security Online Training Course | Ethical Hacking Training Course in Chennai | Certification | Ethical Hacking Online Training Course | CCNA Training Course in Chennai | Certification | CCNA Online Training Course | RPA Robotic Process Automation Training Course in Chennai | Certification | RPA Training Course Chennai | SEO Training in Chennai | Certification | SEO Online Training Course

    ReplyDelete
  34. Гадание на картах на 2020 год значится наиболее достоверным действием просмотреть грядущее человека. Погодные происшествия или церемониальные убийства животных по прошествии длительного времени составили конкретное пояснение обнаруженного. Начальные системы гадания были образованы тысячелетия тому назад до Н.Э.

    ReplyDelete
  35. Её можно использовать в залах организаций общепита, в школах и детских садах. Экологичный материал, фактически безопасен для людей. Керамогранит fabresa base делают в общем из естественных материалов.

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

    ReplyDelete
  37. Thank you for sharing valuable information. its really helpful for me.
    visit: Digital MarketingTraining in Chennai

    ReplyDelete
  38. Дополнительный счет поможет загрести много денег. Регистрируйтесь на платформе и получите специальные очки в учетной записи. Стоит отметить, что проект casino x com мобильная начисляет своим игрокам дополнительные вознаграждения.

    ReplyDelete
  39. Наведавшись в компьютерный клуб, игрок сможет погрузиться в невероятные приключения. Только на странице mr bit играть пользователи очень просто загрузят понравившуюся виртуальную игру для отдыха. Развлекаться в компании друзей намного интереснее, чем самостоятельно на хате.

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

    ReplyDelete
  41. Достойный и авторитетный реализатор всегда сможет предоставить многочисленный подбор керамического покрытия для санузла. Предприятие sotni.ru реализует axima мегаполис мозаика на протяжении 12 лет.

    ReplyDelete
  42. Российские производители довольно давно выполняют производство схожих товаров, многие из которых не уступают западным исходникам. Самой дорогой отделочной плиткой считается итальянская http://www.88joke.com/space-uid-7999.html. Стоимость небольшого квадрата плитки зависит от его внешнего вида, и от страны производства.

    ReplyDelete
  43. Придется мариновать курицу и добавить подходящих пряностей опционально. Насыпьте особенный ингредиент для получения нестандартного вкуса, как пример, корицу. Поджарить сытную курочку без особых заморочек довольно просто https://trebuha.ru/517-ramenovyj-sup.html. Главный секрет находится в этапах обжарки. Ингредиенты для приготовления курицы недорогие, необходимо только мякоть и немного пряности.

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

    ReplyDelete
  45. Приобрести нужный спортинвентарь для отдыха на природе вы имеете возможность благодаря огромному каталогу инвентаря для энергичного отдыха интернет-магазина MegaMag. Настольные игры и атрибутика для активного отдыха тоже будут нужны на открытом воздухе. Кстати, вам могут потребуется купить заварочный чайник в самаре, все разнится от точного места на природе.

    ReplyDelete
  46. Меню какого-либо ресторана непременно имеет рыбные продукты. Повора-самоучки повсеместно предпочитают готовить ракообразных на личной кухне. Здесь https://redgmshop.ru/shop/krevetki/ на удивление легко приобрести рыбу, достаточно сходить в шоу-рум «Красный жемчуг», где имеется истинно великий перечень даров моря.

    ReplyDelete
  47. Иностранному студенту понадобится грубо 15-20 тысяч долларов каждый год на учёбу, количество может изменяться от университета, где происходит учёба. Иностранцы получают обучение в США именно платно. ВУЗы США не дают стипендиальные места иностранцам. Исключительно в силу https://modscheats.ru/348071-obrazovanie-v-ssha-pomosch-v-postuplenii-ot-kompanii-infostudy.html вы можете получить лучшее образование и стартовать успешную карьеру. Особо продвинутые абитуриенты смогут получить на не полную льготу в обучении.

    ReplyDelete
  48. Do you have your iPhone Insurance? If no then connect with the best Mobile Insurance Company and avoid unexpected expenses.

    ReplyDelete
  49. We are known as the best Website designing company in Ghaziabad that have delivered many succesful projects across the world. We can be the right choice for you. Connect with us for more information.

    ReplyDelete
  50. This post is so interactive and informative.keep update more information…
    CCNA course in Anna Nagar
    ccna course in Chennai

    ReplyDelete
  51. Really amazing information, thanks for your efforts for this blog. Thank you so much for sharing this post
    Outdoor Sun Shades Rental Dubai

    ReplyDelete
  52. Looking for the best Ipad insurance? If yes then connect with Assure India to get the best deal. We can be the right choice for you.

    ReplyDelete
  53. Connect with the best SEO Company in dadar that can provide you fully digital marketing solution at an affordable price. Connect with us for more information.

    ReplyDelete
  54. Great post. keep sharing such a worthy information.
    QTP Online Training

    ReplyDelete
  55. If you want to give a new identity to your business through website, and are looking for website builder company, then feel free to contact us, we will solve all your problems so that your business can be a new identity through website.
    Website design company helsinki

    ReplyDelete
  56. If you are looking for a vastu service so you can connect with us , we can be a right choice for you.
    Vastu Consultants in Dubai for Property Planning in Dubai

    ReplyDelete
  57. If you are search best website design company then your search ends here, no one best the CSS Founder, click the given link and finds the best solution Website design company Donetsk

    ReplyDelete
  58. Thanks for providing the best and nice information about it. This is very good. I hope, i will read your next blog soon.
    Medical center in Dublin

    ReplyDelete
  59. If you are looking for an SEO company in Bahrain so you could connect with Promotedial, It can provide you high ranking on googel search engine. For more information please visit our website.

    ReplyDelete
  60. I read every line and word; thank you; and I look forward to the next. If you want to book an online puja, you can call or visit our website.
    Online Pandit Ji Booking for pooja

    ReplyDelete
  61. If you are finding best apartments in Noida Extension then Exotica offers too many projects in Noida like Exotica Dreamville, Exotica Freshco, Exotica square east, Exotica Northville, Exotica elegance etc. Contact for buy or rent apartments in Noida.

    ReplyDelete