Converting date into text format - java

How do I convert date into its text format..for ex:if updated today..then instead of date it must show "Today",one day after it must show "Yesterday",and then after two days..it must display the date in general form(//_) on which it was updated..i tried using SimpleDateFormat..but not working..
SimpleDateFormat sdf = new SimpleDateFormat("dd-MM-yyyy");
Date d= new Date();
//Convert Date object to string
String strDate = sdf.format(d);
System.out.println("Formated String is " + strDate);
d = sdf.parse("31-12-2009");
Plz help..
Thanks in advance..

Try this:
public class TimeUtils {
public final static long ONE_SECOND = 1000;
public final static long SECONDS = 60;
public final static long ONE_MINUTE = ONE_SECOND * 60;
public final static long MINUTES = 60;
public final static long ONE_HOUR = ONE_MINUTE * 60;
public final static long HOURS = 24;
public final static long ONE_DAY = ONE_HOUR * 24;
private TimeUtils() {
}
/**
* converts time (in milliseconds) to human-readable format
* "<w> days, <x> hours, <y> minutes and (z) seconds"
*/
public static String millisToLongDHMS(long duration) {
StringBuffer res = new StringBuffer();
long temp = 0;
if (duration >= ONE_SECOND) {
temp = duration / ONE_DAY;
if (temp > 0) {
duration -= temp * ONE_DAY;
res.append(temp).append(" day").append(temp > 1 ? "s" : "")
.append(duration >= ONE_MINUTE ? ", " : "");
}
temp = duration / ONE_HOUR;
if (temp > 0) {
duration -= temp * ONE_HOUR;
res.append(temp).append(" hour").append(temp > 1 ? "s" : "")
.append(duration >= ONE_MINUTE ? ", " : "");
}
temp = duration / ONE_MINUTE;
if (temp > 0) {
duration -= temp * ONE_MINUTE;
res.append(temp).append(" minute").append(temp > 1 ? "s" : "");
}
if (!res.toString().equals("") && duration >= ONE_SECOND) {
res.append(" and ");
}
temp = duration / ONE_SECOND;
if (temp > 0) {
res.append(temp).append(" second").append(temp > 1 ? "s" : "");
}
return res.toString();
} else {
return "0 second";
}
}
public static void main(String args[]) {
System.out.println(millisToLongDHMS(123));
System.out.println(millisToLongDHMS((5 * ONE_SECOND) + 123));
System.out.println(millisToLongDHMS(ONE_DAY + ONE_HOUR));
System.out.println(millisToLongDHMS(ONE_DAY + 2 * ONE_SECOND));
System.out.println(millisToLongDHMS(ONE_DAY + ONE_HOUR + (2 * ONE_MINUTE)));
System.out.println(millisToLongDHMS((4 * ONE_DAY) + (3 * ONE_HOUR)
+ (2 * ONE_MINUTE) + ONE_SECOND));
System.out.println(millisToLongDHMS((5 * ONE_DAY) + (4 * ONE_HOUR)
+ ONE_MINUTE + (23 * ONE_SECOND) + 123));
System.out.println(millisToLongDHMS(42 * ONE_DAY));
/*
output :
0 second
5 seconds
1 day, 1 hour
1 day and 2 seconds
1 day, 1 hour, 2 minutes
4 days, 3 hours, 2 minutes and 1 second
5 days, 4 hours, 1 minute and 23 seconds
42 days
*/
}
}

Take a look at the PrettyTime library.

You can check this Comparision of dates

import java.text.SimpleDateFormat;
import java.util.Date;
public class App {
SimpleDateFormat sdf = new SimpleDateFormat("dd-MM-yyyy");
public static long ms, s, m, h, d, w;
static {
ms = 1;
s = ms * 1000;
m = s * 60;
h = m * 60;
d = h * 24;
w = d * 7;
}
public App() {
Date now = new Date();
Date old = new Date();
try {
old = sdf.parse("12-11-2013");
} catch (Exception e) {
e.printStackTrace();
}
long diff = now.getTime() - old.getTime();
if (diff < this.d) {
System.out.println("Today");
}
else if (diff > this.d && diff < this.d*2) {
System.out.println("Yesterday");
}
System.out.println("Difference: " + msToHms(diff));
}
public String msToHms(long ms) {
int seconds = (int) (ms / this.s) % 60 ;
int minutes = (int) ((ms / this.m) % 60);
int hours = (int) ((ms / this.h) % 24);
return String.format("%02d:%02d:%02d", hours, minutes, seconds);
}
public static void main(String[] args) {
new App();
}
}
Output
Yesterday
Difference: 07:11:22

You have to implement your own logic based on the time difference and use the corresponding date format.
Lets assume you are getting a date from a server.
Get the device's time and compare to your date.
For your requirements there will be two cases.
The difference between the two date is less then a day, then return "Today" string.
The difference between the two date is grater then a day then use the Simple Date format to format your date as you want.

For comparing dates please see this entry: datecompare

Related

Having trouble developing incrementMinutesBy method

I am trying to create a digital clock an am currently trying to fix my incrementMinutesBy method. 
I need this method to increase both the minutes and if necessary the hours. I need the final this.minutes to be the sum of the previous this.minutes and the parameter, modulo the number of minutes in an hour.
I also need the final this.hours to be the sum of the previous this.minutes and the parameter, divided by the number of minutes in an hour. My method so far begins on line 94.
public class DigitalClock
{
private int currentHour;
private int currentMinutes;
public int getHour()
{
return currentHour;
}
public void setHour(int currentHour)
{
this.currentHour = currentHour;
}
public int getMinutes()
{
return currentMinutes;
}
public void setMinutes(int currentMinutes)
{
this.currentMinutes = currentMinutes;
}
public static final int HOUR_MAX = 23; // Refactored hourly max
public static final int HOUR_MIN = 0; // Refactored hourly min
public static final int MINUTES_MAX = 59; // Refactored minute max
public static final int MINUTES_MIN = 0; // Refactored minute min
public static final int TOTAL_NUMBERS_HOURS = 24;
public static final int TOTAL_NUMBERS_MINUTES = 60;
/**
* Creates a new digital clock with the time set at the given
* hours and minutes.
*
* #precondition 0 <= hour <= 23 AND 0 <= minutes <= 59
* #postcondition getHour()==hour AND getMinutes()==minutes
*
* #param hour the hour to set for the time
* #param minutes the minutes to set for the time
*/
public DigitalClock (int hour, int minutes) // 2-parameter constructor (parameters: int hour and int minutes)
{
// enforcing hourly preconditions using appropriate ranges
if (hour >= HOUR_MIN && hour <= HOUR_MAX){
currentHour = hour;
}
else {
currentHour = 0;
//throw an exception on invalid hour's input
throw new IllegalArgumentException("Invalid input for Hours");
}
// enforcing minute preconditions using appropriate ranges
if (minutes >= MINUTES_MIN && minutes <= MINUTES_MAX) {
currentMinutes = minutes;
}
else {
currentMinutes = 0;
//throw an exception on invalid minute's input
throw new IllegalArgumentException("Invalid input for Minutes");
}
}
/**
* Advances the entire clock by the given number of hours.
* If the hours advances past 23 they wrap around.
*
* #precondition hours >= 0
* #postcondition the clock has moved forward
* by the appropriate number of hours
*
* #param hours the number of hours to add
*/
public void incrementHoursBy(int hour)
{
int h = getHour()+hour; {
// if statement enforcing precondition
if(h>HOUR_MAX)
h%=TOTAL_NUMBERS_HOURS;
// increasing this.hours by the parameter
setHour(h);}
// if statement which prevents negative hours from being inputted
if (h<HOUR_MIN) {
throw new IllegalArgumentException("Invalid input. No negative hours");
}
}
public void incrementMinutesBy(int minutes) {
int m = getMinutes()+minutes;
m++;
if (m > MINUTES_MAX) {
m%=TOTAL_NUMBERS_MINUTES;
setMinutes(m);
}
if (m<MINUTES_MIN) {
throw new IllegalArgumentException("Invalid input. No negative minutes");
}
else
{
System.out.println("Minutes are: "+m);
}
}
public static void main(String args[])
{
DigitalClock obj=new DigitalClock(12, 15);
obj.incrementHoursBy(HOUR_MAX);
obj.incrementMinutesBy(MINUTES_MAX);
DigitalClockFormatter();
}
public static void DigitalClockFormatter() {
// method for class DigitalClockFormatter
}
}
To simplify the implementation, it's beter to save totalMinutes internaly, but not the separate hours and minutes.
public final class DigitalClock {
private static final int MINUTES_PER_HOUR = (int)TimeUnit.HOURS.toMinutes(1);
private static final int MINUTES_PER_DAY = (int)TimeUnit.DAYS.toMinutes(1);
private int totalMinutes;
public DigitalClock(int hour, int minutes) {
setHour(hour);
setMinutes(minutes);
}
public int getHour() {
return totalMinutes / MINUTES_PER_HOUR;
}
public int getMinutes() {
return totalMinutes % MINUTES_PER_HOUR;
}
public void setHour(int hour) {
if (hour < 0 || hour > 23)
throw new IllegalArgumentException("'hour' should be within [0;23]");
totalMinutes = (int)TimeUnit.HOURS.toMinutes(hour) + getMinutes();
}
public void setMinutes(int minutes) {
if (minutes < 0 || minutes > 59)
throw new IllegalArgumentException("'minutes' should be within [0;59]");
totalMinutes = (int)TimeUnit.HOURS.toMinutes(getHour()) + minutes;
}
public void incrementHoursBy(int hour) {
totalMinutes = withinDay((int)TimeUnit.HOURS.toMinutes(hour) + totalMinutes);
}
public void incrementMinutesBy(int minutes) {
totalMinutes = withinDay(totalMinutes + minutes);
}
private static int withinDay(int totalMinutes) {
totalMinutes %= MINUTES_PER_DAY;
if (totalMinutes < 0)
totalMinutes = MINUTES_PER_DAY + totalMinutes;
return totalMinutes;
}
#Override
public String toString() {
return String.format("%02d:%02d", getHour(), getMinutes());
}
}
I believe that your calculations can also be achieved by subtraction. Consider the following example.
If currentHour is 23 and you add two hours, then the result should be 1 (one).
23 + 2 = 25
25 % 24 = 1
25 - 24 = 1
Similarly for currentMinutes. However, for currentMinutes you also need to increment currentHour if the result of the increment (to currentMinutes) is greater than MINUTES_MAX. And when you increment currentHour you also need to check whether the incremented currentHour value is greater than HOUR_MAX. In other words, if currentHour is 23 and currentMinutes is 55 and you incrementMinutesBy(10), then:
55 + 10 = 65
65 - 60 = 5
Therefore currentMinutes is set to 5 and currentHour needs to be incremented. Therefore:
23 + 1 = 24
24 - 24 = 0
So currentHour needs to be set to 0 (zero).
Also, as explained in the book Java by Comparison, methods need to fail fast so the first thing you should do in both method incrementHoursBy and method incrementMInutesBy is to check the value of the method argument – and not the result of the calculation. After all, you wrote in the code comments that the pre-condition is that the method argument not be negative – even though I think it would be logical to be able to set the digital clock backwards. I mean that's what you do when daylight saving ends and the clocks get turned back one hour. But then again, with your [digital] clock, you could achieve the same result by invoking incrementHoursBy(HOUR_MAX)
Consider the following code:
public class DigitalClock {
private int currentHour;
private int currentMinutes;
public int getHour() {
return currentHour;
}
public void setHour(int currentHour) {
this.currentHour = currentHour;
}
public int getMinutes() {
return currentMinutes;
}
public void setMinutes(int currentMinutes) {
this.currentMinutes = currentMinutes;
}
public static final int HOUR_MAX = 23; // Refactored hourly max
public static final int HOUR_MIN = 0; // Refactored hourly min
public static final int MINUTES_MAX = 59; // Refactored minute max
public static final int MINUTES_MIN = 0; // Refactored minute min
public static final int TOTAL_NUMBERS_HOURS = 24;
public static final int TOTAL_NUMBERS_MINUTES = 60;
/**
* Creates a new digital clock with the time set at the given hours and minutes.
*
* #precondition 0 <= hour <= 23 AND 0 <= minutes <= 59
* #postcondition getHour()==hour AND getMinutes()==minutes
*
* #param hour the hour to set for the time
* #param minutes the minutes to set for the time
*/
public DigitalClock(int hour, int minutes) {
// enforcing hourly preconditions using appropriate ranges
if (hour >= HOUR_MIN && hour <= HOUR_MAX) {
currentHour = hour;
}
else {
currentHour = 0;
// throw an exception on invalid hour's input
throw new IllegalArgumentException("Invalid input for Hours");
}
// enforcing minute preconditions using appropriate ranges
if (minutes >= MINUTES_MIN && minutes <= MINUTES_MAX) {
currentMinutes = minutes;
}
else {
currentMinutes = 0;
// throw an exception on invalid minute's input
throw new IllegalArgumentException("Invalid input for Minutes");
}
}
/**
* Advances the entire clock by the given number of hours. If the hours advances
* past 23 they wrap around.
*
* #precondition hours >= 0
* #postcondition the clock has moved forward by the appropriate number of hours
*
* #param hours the number of hours to add
*/
public void incrementHoursBy(int hour) {
// if statement which prevents negative hours from being inputted
if (hour < HOUR_MIN || hour > HOUR_MAX) {
throw new IllegalArgumentException("Invalid input. Between 0 & 23");
}
int h = currentHour + hour;
// if statement enforcing precondition
if (h > HOUR_MAX) {
h -= TOTAL_NUMBERS_HOURS;
}
// increasing this.hours by the parameter
setHour(h);
}
public void incrementMinutesBy(int minutes) {
if (minutes < MINUTES_MIN || minutes > MINUTES_MAX) {
throw new IllegalArgumentException("Invalid input. Between 0 & 59");
}
int m = getMinutes() + minutes;
if (m > MINUTES_MAX) {
incrementHoursBy(1);
m -= TOTAL_NUMBERS_MINUTES;
setMinutes(m);
}
}
public static void main(String args[]) {
DigitalClock obj = new DigitalClock(22, 55);
obj.incrementHoursBy(1);
obj.incrementMinutesBy(10);
DigitalClockFormatter(obj);
}
public static void DigitalClockFormatter(DigitalClock dc) {
System.out.printf("%02d:%02d", dc.getHour(), dc.getMinutes());
}
}
Running above code displays:
00:05
Alternatively, you could use the date-time API.
import java.time.LocalTime;
public class DigiClok {
private LocalTime clock;
public DigiClok(int hour, int minute) {
clock = LocalTime.of(hour, minute); // throws java.time.DateTimeException if invalid arguments
}
public int getHour() {
return clock.getHour();
}
public void setHour(int currentHour) {
// class 'java.time.LocalTime' is immutable.
int minute = clock.getMinute();
clock = LocalTime.of(currentHour, minute);
}
public int getMinutes() {
return clock.getMinute();
}
public void setMinutes(int currentMinutes) {
int hour = clock.getHour();
clock = LocalTime.of(hour, currentMinutes);
}
public boolean equals(Object obj) {
boolean equal = this == obj;
if (!equal) {
if (obj instanceof DigiClok) {
DigiClok other = (DigiClok) obj;
equal = clock.equals(other.clock);
}
}
return equal;
}
public int hashCode() {
return clock.hashCode();
}
public String toString() {
return clock.toString();
}
public void incrementHoursBy(int hour) {
clock = clock.plusHours(hour); // also handles negative 'hour'
}
public void incrementMinutesBy(int minutes) {
clock = clock.plusMinutes(minutes); // also handles negative 'minute'
}
public static void main(String[] args) {
DigiClok obj = new DigiClok(22, 55);
obj.incrementHoursBy(1);
obj.incrementMinutesBy(10);
System.out.println(obj);
}
}

convert time(12h and 24h)

I'm writing a program that converts the time (12h and 24h).
The result I want to get is the following:
convertTime ("12:00") ➞ "0:00"
convertTime ("6:20 pm") ➞ "18:20"
convertTime ("21:00") ➞ "9:00 pm"
convertTime ("5:05") ➞ "5:05"
this is my code, unfortunately the result is not what I expected, in fact:
A time input of 12 hours will be indicated with an am or pm suffix.
An input time of 24 hours contains no suffix.
I would appreciate a help so much, thanks in advance!
public static String convertTime(String time) {
String hour = time.substring(0, time.indexOf(":"));
String min = time.substring(3, time.indexOf(":") + 3);
int hourInteger = Integer.parseInt(hour);
if (hourInteger > 12 && hourInteger < 24) {
hourInteger = hourInteger - 12;
}
if (hourInteger == 24) {
hourInteger = 0;
}
if (hourInteger < 12) {
return hourInteger + ":" + min + " AM";
}
if (hourInteger > 12)
return hourInteger + ":" + min + " PM";
return hourInteger;
}
You can use below code snippet, you can make additional changes accordingly as your wish. Using Date API to parse vise versa 12 <-> 24 Hours format.
public static String convertTime(String time) throws ParseException {
if (time.contains("am") || time.contains("pm")) {
SimpleDateFormat displayFormat = new SimpleDateFormat("HH:mm");
SimpleDateFormat parseFormat = new SimpleDateFormat("hh:mm a");
Date date = parseFormat.parse(time);
return displayFormat.format(date);
} else {
SimpleDateFormat parseFormat = new SimpleDateFormat("HH:mm");
SimpleDateFormat displayFormat = new SimpleDateFormat("hh:mm a");
Date date = parseFormat.parse(time);
return displayFormat.format(date);
}
}
There were few problems with your code.
One is return hourInteger. As the convertTime() return type is String, you can't return an Integer. To convert it you can use,
String.valueOf(hourInteger);
Second in 24h clock format, there is no 24:00. A minute after 23:59 is 00:00. So,
if (hourInteger == 24) {
should be,
if (hourInteger == 0) {
Third,
if (hourInteger > 12 && hourInteger < 24) {
hourInteger = hourInteger - 12;
}
above code will convert all possible hours larger than 12 to hours smaller than 12. So after that line checking if(hourInteger>12) always returns false.
Below code will work for your situation.
public static String convertTime(String time) {
String hour = time.substring(0, time.indexOf(":"));
String min = time.substring(3, time.indexOf(":") + 3);
int hourInteger = Integer.parseInt(hour);
int newHour = hourInteger;
if (hourInteger > 12 && hourInteger < 24) {
newHour = hourInteger - 12;
}
if (hourInteger==0) {
newHour = 12;
}
if (hourInteger < 12) {
return newHour + ":" + min + " AM";
}else {
return newHour + ":" + min + " PM";
}
}
You can use StringTokenizer to split the string into tokens using delimiters : and , then convert based on number of tokens (2 for 24 hour format, 3 for 12 hour format):
import java.util.*;
public class Main
{
public static String convertTime(String time) {
StringTokenizer sb = new StringTokenizer(time, ": ");
if (sb.countTokens() == 2)
{
// 24 hr to 12 hr
int hour = Integer.parseInt(sb.nextToken());
int min = Integer.parseInt(sb.nextToken());
boolean isEvening = false;
if (hour >= 12 && hour <= 24)
{
hour -= 12;
if (hour != 0)
isEvening = true;
}
return String.format("%02d:%02d %s", hour, min, (isEvening ? "pm" : "am"));
}
else if (sb.countTokens() == 3)
{
// 12 hr to 24 hr
int hour = Integer.parseInt(sb.nextToken());
int min = Integer.parseInt(sb.nextToken());
boolean isEvening = sb.nextToken().equalsIgnoreCase("pm");
if (isEvening || hour == 0)
{
hour += 12;
}
return String.format("%02d:%02d", hour, min);
}
return "";
}
public static void main(String[] args) {
System.out.println(convertTime("12:00"));
System.out.println(convertTime("6:20 pm"));
System.out.println(convertTime("21:00"));
System.out.println(convertTime("5:05"));
}
}

How to sum total number of hours ,minutes,seconds in java?

Am having a doubt on how to sum total number of hours minutes seconds in java for example i have 160:00:00 and 24:00:00 and 13:50:00 and 00:10:00 i need to get grand sum like 198:00:00 how can i calculate this so far what i have tried is
for(int i=0;i<addnoteobj.size();i++){
String s = addnoteobj.get(i).getDuration();
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("HH:mm:ss");
simpleDateFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
String[] tokens = s.split(":");
int hours = Integer.parseInt(tokens[0]);
int minutes = Integer.parseInt(tokens[1]);
int seconds = Integer.parseInt(tokens[2]);
duration = 3600 * hours + 60 * minutes + seconds;
int j = duration/3600;
int h= (duration%3600) / 60;
int m = (duration % 60);
hourss=hourss+j;
mm=mm+h;
sss=sss+m;
date3 = hourss + ":" + mm + ":" + ss;
String time = simpleDateFormat.format(new Date(duration*1000L));
Log.d("dat",time);
try {
date=simpleDateFormat.parse(s);
ss=ss+date.getTime();
date3 = simpleDateFormat.format(new Date(ss));
// total=dates.getTime();
Log.d("time",date3);
} catch (ParseException e) {
e.printStackTrace();
}
}
But i cannot achieve this how to do this am having total hours in list how to get total hours thanks in advance
java.time
The java.util Date-Time API and their formatting API, SimpleDateFormat are outdated and error-prone. It is recommended to stop using them completely and switch to the modern Date-Time API*.
Solution using java.time, the modern Date-Time API:
You can use java.time.Duration which is modelled on ISO-8601 standards and was introduced with Java-8 as part of JSR-310 implementation. With Java-9 some more convenient methods were introduced.
Assuming all the string are in the form of HH:mm:ss format, you can split them on : and then combine the parts to form a string in the ISO 8601 pattern for a duration which can be parsed using Duration#parse.
Demo:
import java.time.Duration;
public class Main {
public static void main(String[] args) {
String[] strDurationArr = {
"160:00:00",
"24:00:00",
"13:50:00",
"00:10:00"
};
Duration sum = Duration.ZERO;
for (String strDuration : strDurationArr) {
sum = sum.plus(parseStrDuration(strDuration));
}
System.out.println(formatDurationJava8Plus(sum));
System.out.println(formatDurationJava9Plus(sum));
}
static Duration parseStrDuration(String strDuration) {
String[] arr = strDuration.split(":");
String strIsoDuration = "PT" + arr[0] + "H" + arr[1] + "M" + arr[2] + "S";
return Duration.parse(strIsoDuration);
}
static String formatDurationJava8Plus(Duration duration) {
return String.format("%d:%02d:%02d", duration.toHours(), duration.toMinutes() % 60, duration.toSeconds() % 60);
}
static String formatDurationJava9Plus(Duration duration) {
return String.format("%d:%02d:%02d", duration.toHours(), duration.toMinutesPart(), duration.toSecondsPart());
}
}
Output:
198:00:00
198:00:00
ONLINE DEMO
Learn more about the modern Date-Time API from Trail: Date Time.
* For any reason, if you have to stick to Java 6 or Java 7, you can use ThreeTen-Backport which backports most of the java.time functionality to Java 6 & 7. If you are working for an Android project and your Android API level is still not compliant with Java-8, check Java 8+ APIs available through desugaring and How to use ThreeTenABP in Android Project.
I have intentionally left the println so that you can see the code flow. hope this helps you...
public static void main(String[] args) {
String time[] = { "160:00:00", "24:00:00", "13:50:00", "00:10:00" };
int hours = 0, minutes = 0, seconds = 0;
for (String string : time) {
String temp[] = string.split(":");
hours = hours + Integer.valueOf(temp[0]);
minutes = minutes + Integer.valueOf(temp[1]);
seconds = seconds + Integer.valueOf(temp[2]);
}
System.out.println(hours + ":" + minutes + ":" + seconds);
if (seconds == 60) {
minutes = minutes + 1;
seconds = 0;
} else if (seconds > 59) {
minutes = minutes + (seconds / 60);
seconds = seconds % 60;
}
System.out.println(hours + ":" + minutes + ":" + seconds);
if (minutes == 60) {
hours = hours + 1;
minutes = 0;
} else if (minutes > 59) {
hours = hours + (minutes / 60);
minutes = minutes % 60;
}
System.out.println(hours + ":" + minutes + ":" + seconds);
String output = "";
output = String.valueOf(hours);
output = output.concat(":" + (String.valueOf(minutes).length() == 1 ? "0" + String.valueOf(minutes) : String.valueOf(minutes)));
output = output.concat(":" + (String.valueOf(seconds).length() == 1 ? "0" + String.valueOf(seconds) : String.valueOf(seconds)));
System.out.println(output);
}
I didn't test it but I'm pretty sure it's something like this:
private static String sumTime(String t1, String t2){
byte extraMinutes=0;
byte extraHours=0;
String arrt1[] = t1.split(":");
String arrt2[] = t2.split(":");
int seconds = Integer.valueOf(arrt1[2]) + Integer.valueOf(arrt2[2]);
if(seconds>=60) {
extraMinutes = 1;
seconds = seconds % 60;
}
int minutes = Integer.valueOf(arrt1[1]) + Integer.valueOf(arrt2[1]) + extraMinutes;
if(minutes>=60){
extraHours = 1;
minutes = minutes % 60;
}
int hours = Integer.valueOf(arrt1[0]) + Integer.valueOf(arrt2[0]) + extraHours;
if(hours>=24) hours = hours%24;
return hours+":"+minutes+":"+seconds;
}

Need time difference with string like "A Min ago" or "An Hour Ago" [duplicate]

This question already has answers here:
How to calculate "time ago" in Java?
(33 answers)
Closed 8 years ago.
I am new in Android Development.
I need one help to convert my current time with one static time.
Your help be appreciated.
I have one string like this
String created_at = "Wed Mar 03 19:37:35 +0000 2010";
I want to convert it like , which means difference between my current time and created_at string.
23 mins ago // Example
Thanks,
Dharmik
Just use the following utility class I've created and pass the two date objects in its constructor .Subsequently use the getDifferenceString() method to obtain the same.
public class TimeDifference {
int years;
int months;
int days;
int hours;
int minutes;
int seconds;
String differenceString;
public TimeDifference(Date curdate, Date olddate) {
float diff=curdate.getTime() - olddate.getTime();
if (diff >= 0) {
int yearDiff = Math.round( ( diff/ (365l*2592000000f))>=1?( diff/ (365l*2592000000f)):0);
if (yearDiff > 0) {
years = yearDiff;
setDifferenceString(years + (years == 1 ? " year" : " years") + " ago");
} else {
int monthDiff = Math.round((diff / 2592000000f)>=1?(diff / 2592000000f):0);
if (monthDiff > 0) {
if (monthDiff > 11)
monthDiff = 11;
months = monthDiff;
setDifferenceString(months + (months == 1 ? " month" : " months") + " ago");
} else {
int dayDiff = Math.round((diff / (86400000f))>=1?(diff / (86400000f)):0);
if (dayDiff > 0) {
days = dayDiff;
if(days==30)
days=29;
setDifferenceString(days + (days == 1 ? " day" : " days") + " ago");
} else {
int hourDiff = Math.round((diff / (3600000f))>=1?(diff / (3600000f)):0);
if (hourDiff > 0) {
hours = hourDiff;
setDifferenceString( hours + (hours == 1 ? " hour" : " hours") + " ago");
} else {
int minuteDiff = Math.round((diff / (60000f))>=1?(diff / (60000f)):0);
if (minuteDiff > 0) {
minutes = minuteDiff;
setDifferenceString(minutes + (minutes == 1 ? " minute" : " minutes") + " ago");
} else {
int secondDiff =Math.round((diff / (1000f))>=1?(diff / (1000f)):0);
if (secondDiff > 0)
seconds = secondDiff;
else
seconds = 1;
setDifferenceString(seconds + (seconds == 1 ? " second" : " seconds") + " ago");
}
}
}
}
}
}
}
public String getDifferenceString() {
return differenceString;
}
public void setDifferenceString(String differenceString) {
this.differenceString = differenceString;
}
public int getYears() {
return years;
}
public void setYears(int years) {
this.years = years;
}
public int getMonths() {
return months;
}
public void setMonths(int months) {
this.months = months;
}
public int getDays() {
return days;
}
public void setDays(int days) {
this.days = days;
}
public int getHours() {
return hours;
}
public void setHours(int hours) {
this.hours = hours;
}
public int getMinutes() {
return minutes;
}
public void setMinutes(int minutes) {
this.minutes = minutes;
}
public int getSeconds() {
return seconds;
}
public void setSeconds(int seconds) {
this.seconds = seconds;
}
}
its is simple do something like this ( Note I don't have java etc installed I have just typed it in Note on my ipad, so I am not sure if it works but it should be something like this) :
String dateString = "Wed Mar 03 19:37:35 2010";
SimpleDateFormat dateFormat = new SimpleDateFormat("E M d hh:mm:ss y");
Date convertedDate = new Date();
try {
convertedDate = dateFormat.parse(dateString);
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// convert date to calnedar
Calendar previouseCal = Calendar.getInstance();
previouseCal.setTime(convertedDate );
// then get the current time
Calendar currentCal = Calendar.getInstance();
// then get the diffrence
long difference = currentCal.getTimeInMillis() - previouseCal.getTimeInMillis();
// if you need it in second then
int second = TimeUnit.MILLISECONDS.toSeconds(difference)
I hope that helps :)

Difference between two Date

I want to find difference between 2 Date in months and days using Java. For example: difference between 5/16/2013 and 7/20/2013 is 2 months and 4 days.
Thank you for your consideration on this matter.
Use joda time library as its better to handle dates http://joda-time.sourceforge.net/
Something like this Days.daysBetween(first DateTime, second DateTime).getDays();
I would do it like this
Calendar c1 = new GregorianCalendar(2012, 0, 1);
Calendar c2 = new GregorianCalendar(2013, 0, 2);
int monthDiff = (c2.get(Calendar.YEAR) - c1.get(Calendar.YEAR)) * 12 + c2.get(Calendar.MONTH) - c1.get(Calendar.MONTH);
int dayDiff;
if (c1.get(Calendar.DATE) < c2.get(Calendar.DATE)) {
monthDiff--;
dayDiff = c1.getActualMaximum(Calendar.DAY_OF_MONTH) - c1.get(Calendar.DATE) + c2.get(Calendar.DATE);
} else {
dayDiff = c2.get(Calendar.DATE) - c1.get(Calendar.DATE);
}
System.out.println(monthDiff + " " + dayDiff);
Try this one
java.text.DateFormat df = new java.text.SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
java.util.Date date1 = df.parse("2012-09-30 15:26:14+00");
java.util.Date date2 = df.parse("2012-08-30 15:26:14+00");
int diff = getMonthDifference(date1, date2);
System.out.println(diff);
public static int getMonthDifference(java.util.Date date1, java.util.Date date2) {
if (date1.after(date2)) {
return getMonthDifference0(date1, date2);
} else if (date2.after(date1)) {
return -getMonthDifference0(date2, date1);
}
return 0;
}
private static int getMonthDifference0(java.util.Date date1, java.util.Date date2) {
Calendar c1 = Calendar.getInstance();
Calendar c2 = Calendar.getInstance();
c1.setTime(date1);
c2.setTime(date2);
int diff = 0;
while (c2.getTimeInMillis() < c1.getTimeInMillis()) {
c2.add(Calendar.MONTH, 1);
diff++;
}
int dd = c2.get(Calendar.DAY_OF_MONTH) - c1.get(Calendar.DAY_OF_MONTH);
if (dd > 0) {
diff--;
} else if (dd == 0) {
int hd = c2.get(Calendar.HOUR_OF_DAY) - c1.get(Calendar.HOUR_OF_DAY);
if (hd > 0) {
diff++;
} else if (hd == 0) {
long t1 = c1.getTimeInMillis() % (60 * 1000);
long t2 = c2.getTimeInMillis() % (60 * 1000);
if (t2 > t1) {
diff--;
}
}
}
return diff;
}
Nobody said console.log( new Date("2013-09-30") - new Date("2012-01-01") ); It will give you difference in milliseconds. Its up to you to handle time zones and so forth when creating those 2 objects.

Categories