Java dates difference in milliseconds - java

I've written the following code, but I always just get...
4838399999
Seconds is : 59
Minutes is : 59
Hours is : 23
Days is : 7
Calendar xmas = Calendar.getInstance();
final Calendar now = Calendar.getInstance();
xmas.set(Calendar.YEAR, 2011);
xmas.set(Calendar.MONTH, Calendar.DECEMBER);
xmas.set(Calendar.DAY_OF_MONTH, 25);
long milliseconds1 = now.getTimeInMillis();
long milliseconds2 = xmas.getTimeInMillis();
long diff = milliseconds2 - milliseconds1;
System.out.println(diff);
diff = diff / 1000;
final long diffSeconds = diff % 60;
System.out.println("Seconds is : " + diffSeconds);
diff = diff / 60;
final long diffMinutes = diff % 60;
System.out.println("Minutes is : " + diffMinutes);
diff = diff / 60;
final long diffHours = diff % 60;
System.out.println("Hours is : " + diffHours);
diff = diff / 24;
final long diffDays = diff % 24;
System.out.println("Days is : " + diffDays);
Can anyone see anything wrong with this logic to find the days, hours, minutes and seconds till xmas?

When you do:
diff = diff / 1000;
you're permanently losing the remainder. It should be something like:
long seconds = diff / 1000; // seconds is milliseconds / 1000
long milliseconds = diff % 1000; // remainder is milliseconds that are not composing seconds.
long minutes = seconds / 60;
seconds = seconds % 60;
long hours = minutes / 60;
minutes = minutes % 60;
The same pattern of the last four continues.

These two lines are wrong:
final long diffHours = diff % 60
final long diffDays = diff % 24;
Also, you're not setting the hours/minutes/seconds/milliseconds on xmas, so it gets the hours, minutes, and seconds from the current time. For example, if you run the program at 4:30:20 AM, then it will give you the time until 4:30:20 AM on Christmas. You probably want the time until 00:00:00 on Christmas.

Related

How do I get difference between two dates in android with millisec?

My SimpleDateFormat format is "HH:mm:ss.SSS"
My example time: "00:01:20.442"
How to get (extract) milliseconds 442 to string?
I found code:
long diff = date1.getTime() - date2.getTime();
long mseconds = ?????????;
long seconds = diff / 1000;
long minutes = seconds / 60;
long hours = minutes / 60;
long days = hours / 24;
System.out.println("Milliseconds : "+ String.valueOf(mseconds));
P.S. I'm use API 19 (Adroid 4.4.2)
You take the remainder of dividing by 1000, using the remainder operator:
long mseconds = diff % 1000;
But note that the milliseconds value you've asked for (442) doesn't match what you're doing to get seconds, minutes, etc. In seconds, you'll get the total number of seconds between the dates, which could be in the hundreds of thousands depending on the dates, not just 0-59.
If the goal is to get days, hours (within the day), minutes (within the hour), etc., then:
long mseconds = diff % 1000;
long seconds = (diff / 1000) % 60;
long minutes = (seconds / 60) % 60;
long hours = (minutes / 60) % 24;
long days = hours / 24;
Using the Joda Time library (which in my opinion should be in every project that uses time):
final long millis = DateTime.parse("00:01:20.442", DateTimeFormat.forPattern("HH:mm:ss.SSS")).getMillisOfSecond();
assertEquals(442, millis);
Or, if you want all of them:
final DateTime dt = DateTime.parse("00:01:20.442", DateTimeFormat.forPattern("HH:mm:ss.SSS"));
final long millis = dt.getMillisOfSecond(); //442
final long second = dt.getSecondOfMinute(); //20
final long min = dt.getMinuteOfHour(); //1
final long hour = dt.getHourOfDay(); //0
Why don't you simply split the String by . and use the second element?
Like:
long millis = Long.parseLong(dateStr.split(".")[1]);
Where dateStr is a String of form HH:mm:ss.SSS.
It is much better solution than using a 3rd party library for simple task.

How to calculate the difference in minutes between two timeStamp ( with different days)?

I'm trying to calculate a difference in minutes between two java TimeStamps when I write:
Timestamp t1,t2;
t2.getTime()-t1.getTime();
it returns only the difference between the two times and
I need the difference the whole times (including days)
Try this
long difftime = t1.getTime() - t2.getTime();
long seconds = diff / 1000;
long minutes = seconds / 60;
long hours = minutes / 60;
long days = hours / 24;
Difference between 2 timestamps gives milliseconds. Apply Maths afterwards:
// get time difference in seconds
long milliseconds = timestamp2.getTime() - timestamp1.getTime();
int seconds = (int) milliseconds / 1000;
// calculate hours minutes and seconds
int hours = seconds / 3600;
int minutes = (seconds % 3600) / 60;
seconds = (seconds % 3600) % 60;
Assuming you mean java.sql.Timestamp, the code below seems to work just fine:
import java.sql.Timestamp;
class Scratch {
public static final long MINUTES_PER_HOUR = 60;
public static final long SECONDS_PER_MINUTE = 60;
public static final long HOURS_PER_DAY = 24;
public static final long MILLIS_PER_SECOND = 1000L;
public static void main(String[] args) {
long oneDayPlusFiveMinutesInMillis = (MILLIS_PER_SECOND * SECONDS_PER_MINUTE) * ( 5 + MINUTES_PER_HOUR * HOURS_PER_DAY);
Timestamp t0 = new Timestamp(System.currentTimeMillis());
Timestamp t1 = new Timestamp(t0.getTime() + oneDayPlusFiveMinutesInMillis);
long diff = (t1.getTime() - t0.getTime()) / (MILLIS_PER_SECOND * SECONDS_PER_MINUTE);
System.out.println("t1 - t0 = " + diff + " minutes");
}
}
Returns:
t1 - t0 = 1445 minutes
Timestamp t1 = new Timestamp(new Date("04/26/2019 20:32:49").getTime());
Timestamp t2 = new Timestamp(new Date("04/27/2019 19:32:49").getTime());
long diff = t2.getTime() - t1.getTime();
long diffSeconds = diff / 1000 % 60;
long diffMinutes = diff / (60 * 1000) % 60;
long diffHours = diff / (60 * 60 * 1000) % 24;
long diffDays = diff / (24 * 60 * 60 * 1000);
long diffTotMinutes = diff / (60 * 1000);
System.out.println("Days: " + diffDays + " \nTime: " + diffHours + ":" + diffMinutes + ":" + diffSeconds);
System.out.println("Total Minutes: " + diffTotMinutes);
Out Put:
Days: 0
Time: 23:0:0
Total Minutes: 1380

Simplifying splitting seconds into years, days, etc

I have to code a program which calculates seconds into years, days, hours, minutes, seconds.
My code so far:
public static void main(String[] args) {
long s = IOTools.readLong("Give seconds:");
long a = s / 31536000;
long t = (s % 3153600) / 86400;
long h = ((s % 3153600) % 86400) / 3600;
long m = (((s % 3153600) % 86400) % 3600) / 60;
long r = (((s % 3153600) % 86400) % 3600) % 60;
System.out.println( a + " year(s) " + t + " day(s) " + h + " hour(s) " + m + " minute(s) " + r + " second(s)!");
}
I want to make it simpler, for example with an if-else condition. Something like: divide the seconds by 31536000, save it in a. When there is a remainder, do this, and so on. But I have no idea how to start.
Also I have problems to typecast. I don't want to use long all the time, as it is not necessary anymore when the program calculates the days.
I think the Calendar class here can be pretty handy and you'll avoid complicated calculations. After you read the seconds from the input, you'll just have to convert them into milliseconds and pass the result to a Calendar instance.
Then, you can fetch the day, month, year like this:
long s = IOTools.readLong("Give seconds:");
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(s * 1000);
int year = calendar.get(Calendar.YEAR);
int month = calendar.get(Calendar.MONTH);
int day = calendar.get(Calendar.DAY);
As you suggest you can use the remainder after each step:
long s = IOTools.readLong("Give seconds:");
long a = s / 31536000;
s %= 31536000;
long t = s / 86400;
s %= 86400;
long h = s / 3600;
s %= 3600;
long m = s / 60;
long r = s % 60;
BigDecimal input = new BigDecimal("your input");
long longVal = input.longValue();
int hours = (int) longVal / 3600;
int remainder = (int) longVal - hours * 3600;
int mins = remainder / 60;
remainder = remainder - mins * 60;
int secs = remainder;
System.out.println("hours: "+hours);
System.out.println("Mins: "+mins);
System.out.println("Sec: "+secs)

How to extract a timezone's current time with system.currentTimeMillis()?

public class ShowCurrentTime
{
public static void main(String[] args)
{
// Obtain the total milliseconds
long totalMilliseconds = System.currentTimeMillis();
// Obtain the total seconds
long totalSeconds = totalMilliseconds / 1000;
// Compute the current second in the minute in the hour
long currentSecond = totalSeconds % 60;
// Obtain the total minutes
long totalMinutes = totalSeconds / 60;
// Compute the current minute in the hour
long currentMinute = (totalMinutes % 60);
// Obtain the total hours
long totalHours = totalMinutes / 60;
// Compute the current hour
long currentHour = totalHours % 24;
// Display results
System.out.println("Current time is " + currentHour + ":" + currentMinute + ":" + currentSecond + "GMT");
}
}
Running these codes, gives the GMT, how to configure it to get the current time of a certain timezone like GMT +5:30 (IST)?
times in Java are UTC, if you need to display it in a different timezone you can use the Calendar class and set your desired timezone

I'm making a countdown for android, but I can't realize how to create it

Date lol = c.getTime();
long milli_now = lol.getTime();
c.set(2013, c.MAY, 21);
Date lol1 = c.getTime();
long milli_then = lol1.getTime();
long milli_tot = (milli_then - milli_now);
long sec = (milli_tot/1000);
long min = 0;
long hour = 0;
min = (sec/60);
days.setText("Days left: " + (sec/60/60/24));
countdown.setText(""+hour+":"+min+":"+sec);
What should I do to have it like 216 hours, 60 mins, 60 secs?
I can't figure out the algorithm.
Here is what you can do:
long totDiff = (lastDate.getTime() - firstDate.getTime()); // Total differance in milliseconds
long Sdiff = (totDiff / 1000) % 60; // Differance in seconds
long Mdiff = (totDiff / (60 * 1000)) %60; // Differance in minutes
long Hdiff = (totDiff / (60 * 60 * 1000)); // Remaining time in hours
This should give you the output you're looking for.
What are you getting with this code? As far as I can tell, the only thing you're missing is
hour = min / 60;

Categories

Resources