Posts

Showing posts with the label Java Date Handling

How to convert a String to a Date

In this blog post, I will be demonstrating how you can convert a String to a Date object. Consider the following code snippet: public class StringToDate {public static void main(String[] args) {System.out.println("Enter a date:");Scanner scanner = new Scanner(System.in);String dateStr = scanner.nextLine();System.out.println("Input date is "+dateStr);SimpleDateFormat simpleDateFormat = new SimpleDateFormat("dd-MM-yyyy");try {Date date = simpleDateFormat.parse(dateStr);System.out.println("Date in date format is "+date);} catch (ParseException e) {// TODO Auto-generated catch blocke.printStackTrace();}scanner.close();}} The input Date in String format is read using the  Scanner  class. The code uses the  SimpleDateFormat class. This is a class that provides date formatting functions. In the constructor, you need to specify the format in which the input date is specified as a String. So in this case, I have specified “ dd-MM-yyyy ” which ...

How to find the number of days between two Dates

In this post, I am going to demonstrate how you can find the number of days between two dates. The following code snippet demonstrates this:   Code snippet </pre>public static void main(String[] args) {try {DateFormat df = new SimpleDateFormat("yyyy-MM-dd");Date today = df.parse("2018-08-24");Date future = df.parse("2018-09-04");// Date future = getFutureDate();int daysBetween = daysBetween(today,future);System.out.println("days between = "+daysBetween);} catch (ParseException e) {// TODO Auto-generated catch blocke.printStackTrace();}}private static int daysBetween(Date date1, Date date2){long time1 = date1.getTime(); //Returns no of milliseconds since January 1, 1970, 00:00:00 GMTlong time2 = date2.getTime();long diffInMs = time2-time1;int numOfMsInOneDay = 1000 * 60 * 60 * 24;int daysBetween = (int) (diffInMs / numOfMsInOneDay);return daysBetween;}<pre>   Explanation The Date.getTime method is first used for each Date obj...