How to get current date time – date() and calender()

Yavuz picture Yavuz · Aug 15, 2016 · Viewed 22.4k times · Source

I want hours and minutes will start from the current date will be October 10, 2016 end of days

package com.mkyong.date;

import java.text.SimpleDateFormat;
import java.util.Date;

public class DateDifferentExample
{
    public static void main(String[] args)
    {
        DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
        //get current date time with Date()
        Date date = new Date();
        System.out.println(dateFormat.format(date));
        //get current date time with Calendar()
        Calendar cal = Calendar.getInstance();
        System.out.println(dateFormat.format(cal.getTime()));
        String dateStart = "01/14/2012 09:29:58";
        String dateStop = "01/15/2012 10:31:48";
        //HH converts hour in 24 hours format (0-23), day calculation
        SimpleDateFormat format = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss");
        Date d1 = null;
        Date d2 = null;
        try
        {
            d1 = format.parse(dateStart);
            d2 = format.parse(dateStop);
            //in milliseconds
            long diff = d2.getTime() - d1.getTime();
            long diffSeconds = diff / 1000 % 60;
            long diffMinutes = diff / (60 * 1000) % 60;
            long diffHours = diff / (60 * 60 * 1000) % 24;
            long diffDays = diff / (24 * 60 * 60 * 1000);
            System.out.print(diffDays + " days, ");
            System.out.print(diffHours + " hours, ");
            System.out.print(diffMinutes + " minutes, ");
            System.out.print(diffSeconds + " seconds.");
        }
        catch(Exception e)
        {
            e.printStackTrace();
        }
    }
}

Results :

2016/08/15 18:54:03
2016/08/15 18:54:03
1097 Days1 Hours 1 Minute 50 Second 
My want to result for example :
100 days 5 hours 2 minutes 

Answer

Basil Bourque picture Basil Bourque · Aug 15, 2016

Avoid old date-time classes

You are using troublesome old legacy date-time classes bundled with the earliest versions of Java. Use java.time classes instead.

Parsing

Your input strings are almost in standard ISO 8601 format. Replace the SPACE in the middle with a T. The java.time classes parse/generate strings using ISO 8601 formats by default. So no need to specify a formatting pattern.

String startInput = "01/14/2012 09:29:58".replace( " " , "T" );
String stopInput = "01/15/2012 10:31:48".replace( " " , "T" );

LocalDateTime

Your inputs lack any information about offset-from-UTC or time zone. So we parse as LocalDateTime objects.

LocalDateTime startLdt = LocalDateTime.parse( startInput );
LocalDateTime stopLdt = LocalDateTime.parse( stopInput );

If you work further with these types you will get results based on generic 24-hour days while ignoring anomalies such as Daylight Saving Time (DST).

If you know the context of this data is a particular time zone, apply the zone to get ZonedDateTime.

ZoneId zoneId = ZoneId.of( "America/Montreal" );
ZonedDateTime start = startLdt.atZone( zoneId );
ZonedDateTime stop = stopLdt.atZone( zoneId );

If you want the current moment as the start or the stop, call now. Pass the desired/expected time zone rather than relying on the JVM’s current default time zone.

ZonedDateTime now = ZonedDateTime.now( zoneId );

Duration

The Duration class represents a span of time as a total of seconds plus a fraction of a second in nanoseconds resolution.

Duration duration = Duration.between( start , stop );

Oddly, in Java 8 this class lacks methods to get the number of days, hours, etc. making up this span of time. Java 9 adds to…Part methods.

long days = duration.toDaysPart();
int hours = duration.toHoursPart();
int minutes = duration.toMinutesPart();

Until Java 9 you can do the math yourself.

About java.time

The java.time framework is built into Java 8 and later. These classes supplant the old troublesome date-time classes such as java.util.Date, .Calendar, & java.text.SimpleDateFormat.

The Joda-Time project, now in maintenance mode, advises migration to java.time.

To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations.

Much of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport and further adapted to Android in ThreeTenABP.

The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval, YearWeek, YearQuarter, and more.