I am given a unix timeStamp and I need to calculate the difference between current time and the given unix timestamp like:
2 sec ago
5 mins ago
2 hours ago
3 days ago
So I have written below code:
String time = "given unix timeStamp";
Date date = new Date();
date.setTime(Long.parseLong(time) * 1000);
Calendar start = Calendar.getInstance();
start.setTime(date); // given time
Calendar end = Calendar.getInstance();
end.setTime(new Date()); // current time
Integer[] elapsed = new Integer[6];
Calendar clone = (Calendar) start.clone();
elapsed[0] = elapsed(clone, end, Calendar.YEAR);
clone.add(Calendar.YEAR, elapsed[0]);
elapsed[1] = elapsed(clone, end, Calendar.MONTH);
clone.add(Calendar.MONTH, elapsed[1]);
elapsed[2] = elapsed(clone, end, Calendar.DATE);
clone.add(Calendar.DATE, elapsed[2]);
elapsed[3] = (int) (end.getTimeInMillis() - clone.getTimeInMillis()) / 3600000;
clone.add(Calendar.HOUR, elapsed[3]);
elapsed[4] = (int) (end.getTimeInMillis() - clone.getTimeInMillis()) / 60000;
clone.add(Calendar.MINUTE, elapsed[4]);
elapsed[5] = (int) (end.getTimeInMillis() - clone.getTimeInMillis()) / 1000;
submissionTime.setText(elapsed[0] + " years," + elapsed[1] + " months,"
+ elapsed[2] + " days," + elapsed[3] + " hours," + elapsed[4]
+ " minutes," + elapsed[5] + " seconds");
And this is the elapsed() function:
public static int elapsed(Calendar before, Calendar after, int field) {
Calendar clone = (Calendar) before.clone();
int elapsed = -1;
while (!clone.after(after)) {
clone.add(field, 1);
elapsed++;
}
return elapsed;
}
But this is giving me wrong input. I am new in Java/Android date manipulation and some full working code will be helpful.
Related
Good day.I am building an chat application.For purpose i decided to put a date of message had been sent.No wounder that in different countries the date must show different.For example let's take 2 different countries and assume the difference between them are 2 hours.CountryX and CountryY.The user send message from CountryX which time is lets say 15:00.I am saving this on server with exact timezone time as user sent,exactly 15:00 as CountryX.Second user receives the message in CountryY which is more in 2 hours from CountryX,so basically The time which I MUST show in CountryY must be 17:00.This is the issue.How can i convert an already received time with known timezone to local in order to show correct?I did google a lot but all i came up,were solutions where you would simply just get an time for exact country,and not convert the CountryX sent Time to CountryY local time to show it correctly in CountryY.Please can you provide an help?Thank you very much beforehand.
For everyone suffering because of this.I have ended up creating my own class with my own logic and it works flawlessly and as an extra bonus couple of handy methods with time
public class Time {
public static String getCurrentTime() {
Calendar calendar = Calendar.getInstance();
int year = calendar.get(Calendar.YEAR);
int month = calendar.get(Calendar.MONTH) + 1;
int day = calendar.get(Calendar.DAY_OF_MONTH);
int hour = calendar.get(Calendar.HOUR_OF_DAY);
int minute = calendar.get(Calendar.MINUTE);
int second = calendar.get(Calendar.SECOND);
String finalFormat = year + "-" + month + "-" + day + " " + hour + ":" + minute + ":" + second;
if (month < 10) {
String finalMonth = "0" + month;
finalFormat = year + "-" + finalMonth + "-" + day + " " + hour + ":" + minute + ":" + second;
}
return finalFormat;
}
public static String convertToLocalTime(String timeToConvert) {
SimpleDateFormat sourceFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
sourceFormat.setTimeZone(TimeZone.getTimeZone(Constants.SERVER_TIME_ZONE));//where server time zone is the time zone of your server as defauul,E.X -America/Los_Angeles
Date parsed;
try {
parsed = sourceFormat.parse(timeToConvert);
} catch (ParseException e) {
e.printStackTrace();
return "";
}
TimeZone tz = TimeZone.getDefault();
SimpleDateFormat destFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
destFormat.setTimeZone(tz);
String result = destFormat.format(parsed);
return result;
}
public static String getTimeZone() {
return TimeZone.getDefault().getID();
}
}
all my code is in timer and it tik every 2 seconds
I have 3 different times
1) Time from the time picker(sTime).
2) Get Current time of my phone(cTime).
3) Expiry Time - (for creating range between timepicker's time and expiry time) (rTime).
I want to silent my phone when cTime is equal or after sTime
and turn back my phone profile to normal when cTime is equal or after rTime
but i cannot achieve this. i have done my coding and i think logic is fine but why its not working. please help me in this regard.
Here is my code
AudioManager am;
am = (AudioManager) getBaseContext().getSystemService(Context.AUDIO_SERVICE);
try {
SimpleDateFormat sdf = new SimpleDateFormat("HH:mm");
String savedTime = sHour + ":" + sMin;
Date sTime = sdf.parse(savedTime);
Calendar c = Calendar.getInstance();
int currentHour = c.get(Calendar.HOUR);
int currentMin = c.get(Calendar.MINUTE);
String currentTime = currentHour + ":" + currentMin;
Date cTime = sdf.parse(currentTime);
int rangeHour = sHour;
int rangeMin = sMin + 1;
Date rTime = sdf.parse(rangeHour + ":" + rangeMin);
if (cTime.after(sTime)) {
am.setRingerMode(AudioManager.RINGER_MODE_VIBRATE);
Log.e("res", "Silent Mode Timing");
}
if (cTime.after(rTime)) {
am.setRingerMode(AudioManager.RINGER_MODE_NORMAL);
Log.e("res", "Normal Mode Timing");
}
} catch (Exception ex) {
Log.e("res", ex.toString());
}
Ok, I have a suggestion. The method 'after' of Date class compare two long values in milliseconds. When you get current time milliseconds value it calculate as current year + current month + current day and hour etc. (or something like this). And when you get milliseconds of you savedTime it calculates incorrect because you not specify full Date (year, etc). I mean that you startTime incorrect when it convert in long milliseconds value in Date.after method. try to change you algorithm to work wit long timestamp, not with Date. for example current time is System.currentTimeMillis(). I hope it help. Sorry for my English
Ok, try to use something like this:
private void compareTime(final String year, final String day, final String hour, final String month, final String minutes) {
AudioManager am;
am = (AudioManager) getBaseContext().getSystemService(Context.AUDIO_SERVICE);
final SimpleDateFormat sdf = new SimpleDateFormat("hh:mm:dd:mm:yy");
final String savedTimeValue = hour + ":" + minutes + ":" + day + ":" + month + ":" + year;
try {
final Date savedDate = sdf.parse(savedTimeValue);
final long savedTime = savedDate.getTime();
final long currentTime = System.currentTimeMillis();
final long rangeTimeMilliseconds = 1 * 60 * 1000; // 1 minute in milliseconds
if (currentTime > savedTime) {
am.setRingerMode(AudioManager.RINGER_MODE_VIBRATE);
}
if (currentTime > rangeTimeMilliseconds) {
am.setRingerMode(AudioManager.RINGER_MODE_NORMAL);
}
}catch(Exception e) {
e.printStackTrace();
}
}
Hi i need to convert milliseconds (1437790538 its 25 july 2015) to seconds but when i trying to convert seconds then it not work i get irrelevant result.From last two days very stressed from these result.
i have use this code for doing this purpose
long duration_seconds = 1437790538;
Calendar calendar = Calendar.getInstance();
TimeZone tz = TimeZone.getDefault();
calendar.setTimeInMillis(duration_seconds * 1000);
calendar.add(Calendar.MILLISECOND,
tz.getOffset(calendar.getTimeInMillis()));
SimpleDateFormat sdf = new
SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date currenTimeZone = (Date) calendar.getTime();
String resultabc = sdf.format(currenTimeZone);
long curMillis = currenTimeZone.getTime() / 1000;
// long seconds = (curMillis/ 1000) % 60;
Log.e("test", "datee1 :" + resultabc + " , " + curMillis + " , " + seconds);
getDurationBreakdown(curMillis);
calculateTime(seconds);
after i need to calculate total time of post like this
public static void calculateTime(long seconds) {
int day1 = (int) TimeUnit.SECONDS.toDays(seconds);
long hours1 = TimeUnit.SECONDS.toHours(seconds) - (day1 * 24);
long minute1 = TimeUnit.SECONDS.toMinutes(seconds)
- (TimeUnit.SECONDS.toHours(seconds) * 60);
long second1 = TimeUnit.SECONDS.toSeconds(seconds)
- (TimeUnit.SECONDS.toMinutes(seconds) * 60);
Log.e("test", "time interval ::" + "Day " + day1 + " Hour " + hours1
+ " Minute " + minute1 + " Seconds " + second1);
// int days, hours, mins, seconds, justnow;
days = (int) day1;
hours = (int) hours1;
mins = (int) minute1;
seconds = (int) second1;
System.out.println("Day " + day1 + " Hour " + hours1 + " Minute1 "
+ minute1 + " Seconds " + second1);
public static String getDurationBreakdown(long millis)
{
if(millis < 0)
{
throw new IllegalArgumentException("Duration must be greater than zero!");
}
long days = TimeUnit.MILLISECONDS.toDays(millis);
millis -= TimeUnit.DAYS.toMillis(days);
long hours = TimeUnit.MILLISECONDS.toHours(millis);
millis -= TimeUnit.HOURS.toMillis(hours);
long minutes = TimeUnit.MILLISECONDS.toMinutes(millis);
millis -= TimeUnit.MINUTES.toMillis(minutes);
long seconds = TimeUnit.MILLISECONDS.toSeconds(millis);
StringBuilder sb = new StringBuilder(64);
sb.append(days);
sb.append(" Days ");
sb.append(hours);
sb.append(" Hours ");
sb.append(minutes);
sb.append(" Minutes ");
sb.append(seconds);
sb.append(" Seconds");
Log.e("test", "time interval" + sb.toString());
return(sb.toString());
}
}
both methods giving wrong result.
if anybody have idea how to do this thing in correct way please help me out this problem..
thanks in advance
Your
long curMillis = currenTimeZone.getTime() / 1000;
seems misleading. .getTime() will give you the time in millis, so dividing it by 1000 you will get secs not milis...
UPDATE
As far as I understand your code you simply want to calculate the difference between a given date (represented in secs) and the actual date. For that you can just do
long myDateInSecs = 1437790538; // 25 july 2015
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(myDateInSecs * 1000);
Calendar calendarNow = Calendar.getInstance();
long diff = calendarNow.getTime() - calendar.getTime();
long seconds = TimeUnit.MILLISECONDS.toSeconds(diff);
long minutes = TimeUnit.MILLISECONDS.toMinutes(diff);
...
seconds % 60
1437790538 % 60 -> 38
1437790538 is a timestamp in seconds, not in milliseconds.
I want to calc the time differnce from when the user pressed start and stop.
This is what I got so far:
Done in not worker thread:
runTime = System.currentTimeMillis();
Done on main thread:
DateFormat formatter = new SimpleDateFormat("hh:mm:ss.SSS");
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(System.currentTimeMillis() - runTime);
timeTextView.setText("Time: " + formatter.format(calendar.getTime()));
The result is always "01:00:00.000".
How come I get a 1hour added to the time?
And ofc I press the start and stop button faster then one hour.
The result you have is the time since epoch in java, So if you try to print
timeTextView.setText("Time: " + calendar.getTime().toString());
You are more likely to have the result of Wed Dec 31 19:00:00 EST 1969 depends on which TimeZone you currently are. From your code above I got 07:00:00:000 because I am at EST TimeZone. You cant really do about it but it eliminate the hh so it will only show the minutes, seconds, and milliseconds.
A simple way of solving (working around ?) this issue:
long startTime = System.currentTimeMillis();
//* do something
long endTime = System.currentTimeMillis();
long elapsedTimeInMilliSecs=(endTime - startTime);
Calendar ...
I use something like this and it works fine.
Try this if you just want your elapsed time in HH:MM:SS, this works even if you have more than 24 hours.
timeTextView.setText("Time: " + convertMillis(System.currentTimeMillis() - runTime));
...
public static String convertMillis(long milliseconds){
long time = milliseconds / 1000;
String seconds = Integer.toString((int)(time % 60));
String minutes = Integer.toString((int)((time % 3600) / 60));
String hours = Integer.toString((int)(time / 3600));
for (int i = 0; i < 2; i++) {
if (seconds.length() < 2) {
seconds = "0" + seconds;
}
if (minutes.length() < 2) {
minutes = "0" + minutes;
}
if (hours.length() < 2) {
hours = "0" + hours;
}
}
return(hours + ":" + minutes + ":" + seconds);
}
I'm developing an Android App and I need to calculate some times (with Joda libs).
I would like to know if exist a Java class who does this.
The cases that I would like to calculate (in example):
Case 1:
t1 = "13:40"
t2 = "12:30"
result = t1 + t2 --> 26:10
Case 2:
t1 = "13:40"
t2 = "12:30"
result = t1 - t2 --> 1:10
Case 2.1:
t1 = "13:40"
t2 = "14:00"
result = t1 - t2 --> -0:20
Thanks!! :)
Following JodaTime-code handles both inputs and result as temporal amounts, not points in time:
CASE 1:
PeriodFormatterBuilder builder = new PeriodFormatterBuilder();
builder.minimumPrintedDigits(2);
builder.printZeroAlways();
builder.appendHours();
builder.appendLiteral(":");
builder.appendMinutes();
PeriodFormatter pf = builder.toFormatter();
Period period1 = pf.parsePeriod("13:40");
Period period2 = pf.parsePeriod("12:30");
Period total = period1.plus(period2);
Period normalized = total.normalizedStandard(PeriodType.time());
System.out.println("TOTAL PERIOD: " + total); // PT25H70M
System.out.println("NORMALIZED PERIOD: " + normalized); // PT26H10M
System.out.println("FORMATTED NORMALIZED PERIOD: " + pf.print(normalized)); // 26:10
CASE 2 + 2.1:
PeriodFormatterBuilder builder = new PeriodFormatterBuilder();
builder.minimumPrintedDigits(2);
builder.printZeroAlways();
builder.appendHours();
builder.appendLiteral(":");
builder.appendMinutes();
PeriodFormatter pf = builder.toFormatter();
Period period1 = pf.parsePeriod("13:40");
Period period2 = pf.parsePeriod("14:00");
boolean negative = false;
if (period1.toStandardDuration().isShorterThan(period2.toStandardDuration())) {
Period tmp = period1;
period1 = period2;
period2 = tmp;
negative = true;
}
Period total = period1.minus(period2);
Period normalized = total.normalizedStandard(PeriodType.time());
System.out.println("NORMALIZED PERIOD: " + (negative ? "-" : "") + normalized);
System.out.println(
"FORMATTED NORMALIZED PERIOD: " + (negative ? "-" : "") + pf.print(normalized)
); // -00:20
Note that due to insufficient sign handling of JodaTime (which likes to print the sign not in front but midth inside period expression) some clunky workaround is necessary.
I calculate here 05:00:00 PM this format you can take any format which you want:
String string1 = "05:00:00 PM";
Date time1 = new SimpleDateFormat("HH:mm:ss aa").parse(string1);
Calendar calendar1 = Calendar.getInstance();
calendar1.setTime(time1);
String string2 = "09:00:00 AM";
Date time2 = new SimpleDateFormat("HH:mm:ss aa").parse(string2);
Calendar calendar2 = Calendar.getInstance();
calendar2.setTime(time2);
calendar2.add(Calendar.DATE, 1);
Date x = calendar1.getTime();
Date xy = calendar2.getTime();
long diff = x.getTime() - xy.getTime();
diffMinutes = diff / (60 * 1000);
float diffHours = diffMinutes / 60;
System.out.println("diff hours" + diffHours);