Solved

Getting duration in hours and minutes from a given date using Java

Posted on 2010-11-18
14
511 Views
Last Modified: 2013-11-24
Hi experts,
I have a date in the format  2010-11-19T04:45:47.000Z which is a String.


Depending on the posted time, I am able to obtain the days ago, months ago and years ago perfectly, using the given piece of code and it works perfect.

Can you please help me by giving me the direction as to how can I get the hours if Integer.parseInt(date)< 1

ie; if the posted date is less than a day, I should get the hours and if it is less than a hour, I need to get it in minutes.

I have been pulling out my hairs in finding a solution for the same.

Any doubt in the question I have posted here or the code I have placed here, please let me know.

Any help in this regard which will guide me to a solution will be well appreciated and awarded with points.

Looking forward,
Warm Regards,
Sreejith
String date = daysBetween2Dates(comment.getDate()).toString();

		

		if(Integer.parseInt(date)<= 31){

			tvPosted.setText(date + " days ago");

		 }else if(Integer.parseInt(date)> 31 && Integer.parseInt(date)<= 360){

			 Integer month = Integer.parseInt(date)/30;

			 tvPosted.setText(month.toString()+ " months ago");

		 }else if (Integer.parseInt(date)> 360){

			 Integer years = Integer.parseInt(date)/360;

			 tvPosted.setText(years.toString()+ " years ago");

		 }













public static Long daysBetween2Dates(String date){

		

		String[] new_s = date.split("T");

		String[]  name = new_s[0].split("-");

		Calendar c1 = Calendar.getInstance(); 	//new GregorianCalendar();

		Calendar c2 = Calendar.getInstance(); 	//new GregorianCalendar();

	    c1.set(Integer.parseInt(name[0]), Integer.parseInt(name[1])-1 , Integer.parseInt(name[2])); 

	   

	    Long days = ((c2.getTime().getTime() - c1.getTime().getTime())/(24*3600*1000));

	 

	    return days;

	}

Open in new window

0
Comment
Question by:Sreejith22
  • 6
  • 4
  • 4
14 Comments
 
LVL 92

Expert Comment

by:objects
ID: 34170540
0
 

Author Comment

by:Sreejith22
ID: 34170674
Hi Objects,

I tried your code.

The problem here is, I get 0 returned using my code, which calculates the difference between two dates.

But that same code works perfect for year, month and days, not for hours and minutes, since the difference calculating method returns zero for hours and minutes.

sample date which returns zero from my daysBetween2Dates method -- 2010-11-19T06:05:51.000Z


Kindly help
public static Long daysBetween2Dates(String date){

		

		String[] new_s = date.split("T");

		String[]  name = new_s[0].split("-");

		Calendar c1 = Calendar.getInstance(); 	//new GregorianCalendar();

		Calendar c2 = Calendar.getInstance(); 	//new GregorianCalendar();

	    c1.set(Integer.parseInt(name[0]), Integer.parseInt(name[1])-1 , Integer.parseInt(name[2])); 

	   

	    Long days = ((c2.getTime().getTime() - c1.getTime().getTime())/(24*3600*1000));

	    System.out.println("difference is "+days);

	    return days;

	}

Open in new window

0
 
LVL 92

Assisted Solution

by:objects
objects earned 150 total points
ID: 34170744
The link I posted shows how to calc day,hours, minutes and seconds.
The approach you are using is a bit limited

you're method for parsing the string could also be simplified

http://helpdesk.objects.com.au/java/how-do-i-parse-a-java-string-that-specifies-a-date
0
 

Author Comment

by:Sreejith22
ID: 34171112
Hi,
So you suggest me to change the string format which I have - 2010-11-19T06:05:51.000Z to the format shown in link - 06:23 01/05/06

Correct?
0
 
LVL 86

Accepted Solution

by:
CEHJ earned 350 total points
ID: 34171126
Try something like the below

http://technojeeves.com/joomla/index.php/free/71-difference-between-two-dates-in-java
Date d1 = java.sql.Timestamp.valueOf(cleanTimestamp("2010-11-19T04:45:47.000Z"));

	Date d2 = new java.sql.Timestamp(System.currentTimeMillis());

	long[] diffs = TimeDiff.getTimeDifference(d1, d2);

	TimeDiff.printDiffs(diffs);

    ................



    static String cleanTimestamp(String ts) {

	return ts.substring(0, ts.length() - 1).replaceAll("T", " ");

    }

Open in new window

0
 
LVL 92

Expert Comment

by:objects
ID: 34171146
> So you suggest me to change the string format which I have - 2010-11-19T06:05:51.000Z to the format shown in link - 06:23 01/05/06

no the other way round. You would change the format string to match the format you are using.
0
 

Author Comment

by:Sreejith22
ID: 34171161
CEHJ,
Thanks a lot for that snippet. Let me try that out.
0
Better Security Awareness With Threat Intelligence

See how one of the leading financial services organizations uses Recorded Future as part of a holistic threat intelligence program to promote security awareness and proactively and efficiently identify threats.

 

Author Comment

by:Sreejith22
ID: 34171422
CEHJ,
Thanks a lot. It worked like a charm.

I got the following output for the given date.

day 0
hour 10
minute 8
second 54
millisecond 245


Would have been awesome, if I could get the month and year also. If so, I need not write another method for calculating month and year.

Regards,
Sree
Timestamp d1 = java.sql.Timestamp.valueOf(cleanTimestamp("2010-11-19T04:45:47.000Z"));

	Timestamp d2 = new java.sql.Timestamp(System.currentTimeMillis());

	long[] diffs = TimeDiff.getTimeDifference(d1, d2);

	//The fields day, hour, minute, second and millisecond

	System.out.println("day"+diffs[0]);

	System.out.println("hour"+diffs[1]);

	System.out.println("minute"+diffs[2]);

	System.out.println("second"+diffs[3]);

	System.out.println("millisecond"+diffs[4]);

Open in new window

0
 
LVL 92

Expert Comment

by:objects
ID: 34171476
code which does exactly what I linked to above :)

0
 
LVL 86

Expert Comment

by:CEHJ
ID: 34171587
>>Would have been awesome, if I could get the month and year also

Year is possible. Month is not, since a month has no fixed period. Actually the cleaning routine would be more portable as:
static String cleanTimestamp(String ts) {

	return ts.substring(0, ts.length() - 1).replace('T', ' ');

    }

Open in new window

0
 

Author Comment

by:Sreejith22
ID: 34171921
final int ONE_YEAR = ONE_DAY*365;
long y = diff / ONE_YEAR;
        diff %= ONE_YEAR;

result[5] = y;


I chaanged the date to 2007-11-19T04:45:47.000Z in order to check this, but the year returned is zero.

Please advise.
0
 

Author Comment

by:Sreejith22
ID: 34172009
Hi,
Sorry to post that foolish query!!
0
 
LVL 86

Expert Comment

by:CEHJ
ID: 34172145
>>final int ONE_YEAR = ONE_DAY*365;

That of course is only approximate - it's not true of leap years

>>the year returned is zero

It will be if it's a partial 'year'. What are the two dates?
0
 
LVL 86

Expert Comment

by:CEHJ
ID: 34311541
:)
0

Featured Post

Enabling OSINT in Activity Based Intelligence

Activity based intelligence (ABI) requires access to all available sources of data. Recorded Future allows analysts to observe structured data on the open, deep, and dark web.

Join & Write a Comment

Are you developing a Java application and want to create Excel Spreadsheets? You have come to the right place, this article will describe how you can create Excel Spreadsheets from a Java Application. For the purposes of this article, I will be u…
Go is an acronym of golang, is a programming language developed Google in 2007. Go is a new language that is mostly in the C family, with significant input from Pascal/Modula/Oberon family. Hence Go arisen as low-level language with fast compilation…
Viewers learn about the “while” loop and how to utilize it correctly in Java. Additionally, viewers begin exploring how to include conditional statements within a while loop and avoid an endless loop. Define While Loop: Basic Example: Explanatio…
Video by: Michael
Viewers learn about how to reduce the potential repetitiveness of coding in main by developing methods to perform specific tasks for their program. Additionally, objects are introduced for the purpose of learning how to call methods in Java. Define …

758 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

19 Experts available now in Live!

Get 1:1 Help Now