Solved

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

Posted on 2010-11-18
14
514 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
Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

 

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

Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

Question has a verified solution.

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

Suggested Solutions

Title # Comments Views Activity
best (free) software to access postgres db (java) 1 32
maven project error 5 44
Java Timer (static) 9 36
custom annotations 9 28
I had a project requirement for a displaying a user workbench .This workbench would consist multiple data grids .In each grid the user will be able to see a large number of data. These data grids should allow the user to 1. Sort 2. Export the …
In this post we will learn how to connect and configure Android Device (Smartphone etc.) with Android Studio. After that we will run a simple Hello World Program.
This tutorial covers a step-by-step guide to install VisualVM launcher in eclipse.
Viewers will learn how to properly install Eclipse with the necessary JDK, and will take a look at an introductory Java program. Download Eclipse installation zip file: Extract files from zip file: Download and install JDK 8: Open Eclipse and …

943 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

8 Experts available now in Live!

Get 1:1 Help Now