?
Solved

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

Posted on 2010-11-18
14
Medium Priority
?
527 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
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 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 600 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
Optimize your web performance

What's in the eBook?
- Full list of reasons for poor performance
- Ultimate measures to speed things up
- Primary web monitoring types
- KPIs you should be monitoring in order to increase your ROI

 

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 1400 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
 

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

VIDEO: THE CONCERTO CLOUD FOR HEALTHCARE

Modern healthcare requires a modern cloud. View this brief video to understand how the Concerto Cloud for Healthcare can help your organization.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

By the end of 1980s, object oriented programming using languages like C++, Simula69 and ObjectPascal gained momentum. It looked like programmers finally found the perfect language. C++ successfully combined the object oriented principles of Simula w…
A solution for Fortify Path Manipulation.
The viewer will learn how to implement Singleton Design Pattern in Java.
This tutorial will introduce the viewer to VisualVM for the Java platform application. This video explains an example program and covers the Overview, Monitor, and Heap Dump tabs.
Suggested Courses
Course of the Month11 days, 3 hours left to enroll

770 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