Current Time In Java(Logic Error) Time Zone: US Eastern Time - java

I seem to have a logic error in my code. The time now is: 14:38, but
my code says 18:38. I know there's a Calendar class I could use, but I want to
know why this code was wrong.
Code below:
public class welcome{
public static void main(String args[]){
//get total milliseconds since 1970
long total_millisec = System.currentTimeMillis();
// compute total seconds since 1970
long total_sec = total_millisec / 1000;
//compute current second
long current_sec = total_sec % 60;
//compute total minutes since epoch
long total_mins = total_sec / 60;
//compute current minute
long current_min = total_mins % 60;
//compute total hours
long total_hours = total_mins / 60;
//compute current hour
long current_hour = total_hours % 24;
System.out.println("Time is: "+current_hour+":"+current_min+":"
+current_sec);
}
}

When you perform your calculation, it's presumed that System.currentTimeMillis() returns difference in milliseconds between midnight of 1st January of 1970 (which is 1970-01-01 00:00) and current time. Try to evaluate the base date in your system and see what it'll be:
System.out.println("" + new java.text.SimpleDateFormat("yyyy-MM-dd HH:mm").format(new java.util.Date(0)));
it might return something like 1969-12-31 19:00 and this is not the midnight.
System.currentTimeMillis() returns the same as expression:
long currentTime = new java.util.Date().getTime() - new java.util.Date(0).getTime();

Related

How can you check if a given time in milliseconds was yesterday?

Given a time in milliseconds, how can you check if it was yesterday?
You would first convert the millis to a Date or LocalDate and then run the comparison.
Here's a quick example:
import java.time.*;
class DateCheckSample {
public static void main(String[] args) {
// Our input date
long millis = System.currentTimeMillis();
// Convert the millis to a LocalDate
Instant instant = Instant.ofEpochMilli(millis);
LocalDate inputDate = instant.atZone(ZoneId.systemDefault()).toLocalDate();
// Grab today's date
LocalDate todaysDate = LocalDate.now();
System.out.println(millis);
// Check if date is yesterday
if (todaysDate.minusDays(1).equals(inputDate)) {
System.out.println(inputDate + " was yesterday!");
} else {
System.out.println(inputDate + " was NOT yeseterday!");
}
}
}
The Result:
2019-02-16 was NOT yesterday!
If you'd like to confirm it's working, just subtract 100000000 from millis before running.
Side Note: As pointed out in the comments on your question, 23:59 is not a millis value...
If you don't want to use Date, you can simply use the modulus operator with a bit of clever arithmetics. System#currentTimeMillis returns the amount of milliseconds that have passed since January 1, 1970, midnight (00:00).
Combining this with the number of milliseconds in a day (86,400,000), we can figure the time at which the last start of day was — which is when today began. Then we can see if the time given to us is smaller or larger than that value.
boolean isToday(long milliseconds) {
long now = System.currentTimeMillis();
long todayStart = now - (now % 86400000);
if(milliseconds >= todayStart) {
return true;
}
return false;
}
To check if a time is yesterday instead of today, we simply check if it is between the start of today and the start of yesterday.
boolean isYesterday(long milliseconds) {
long now = System.currentTimeMillis();
long todayStart = now - (now % 86400000);
long yesterdayStart = todayStart - 86400000;
if(milliseconds >= yesterdayStart && < todayStart) {
return true;
}
return false;
}
You can convert the milliseconds to Date and then compare the day with today's Date.
For reference: Convert millisecond String to Date in Java

Calculating days, hours, minutes, seconds, until 2038

I need to get the days,hours, minutes, seconds from current time till 2038.I am having issues with the output.
public class Assignment1 {
public static void main(String[] args) {
long now = System.currentTimeMillis();
long y2k38 = (long) Math.pow(2, 31)*1000;
long diffmillis = y2k38-now;
long diffsec = (y2k38-now)/1000;
long diffmin = diffsec/60;
long diffhours = diffmin/60;
long diffdays = diffhours/24;
System.out.printf(
"Y2K38 will occur in %d days.\n"+
"Y2K38 will occur in %d hours.\n"+
"Y2K38 will occur in %d minutes.\n"+
"Y2K38 will occur in %d seconds.\n",
(diffdays%24),(diffhours%60), (diffmin%60),(diffsec%60));
}
}
Your main issue is that your diffdays, diffhours, diffmin, and diffsec are all just constants that don't actually interact with the current timestamp, so y2k38-diffdays, y2k38-diffhours, and y2k38-diffmin are simply constants subtracting constants.
You will likely want to calculate the number of milliseconds until 2038 with y2k38-now, and then convert up to the units you want from there.
For example, (y2k38-now)/1000 should give you seconds until 2038, (y2k38-now)/(60*1000) should give you minutes, etc.

How to add two Milliseconds in android

I want to calculate difference between two times which is calculate correctly then i have to half it so i divide it with 2 results are okay. but when i am trying to add the timdedifferencemillis to startTime its not giving me the correct result...
starttime= 05:53
endtime= 17:57
i want results 11:55
but my code giving me 06:55
please help.....
protected String transitTime2(String endtime, String starttime) {
SimpleDateFormat dt = new SimpleDateFormat("hh:mm");
Date startTime = null;
Date endTime;
long timdedifferencemillis = 0;
try {
startTime = dt.parse(starttime);
endTime = dt.parse(endtime);
long diff=startTime.getTime();
timdedifferencemillis = (endTime.getTime() - startTime.getTime())/2;
//timdedifferencemillis
} catch (ParseException e) {
e.printStackTrace();
}
long timdedifferencemillis1=startTime.getTime()+timdedifferencemillis;
int minutes = Math
.abs((int) ((timdedifferencemillis1 / (1000 * 60)) % 60));
int hours = Math
.abs((int) ((timdedifferencemillis1 / (1000 * 60 * 60)) % 24));
String hmp = String.format("%02d %02d ", hours, minutes);
return hmp;
}
The problem is probably time zone; when you parse endtime and starttime initially, by default (in the absence of an explicit time zone indicated in the format string and represented in the input), Java assumes that the times provided are relative to the local time zone of the system. Then, when you call getTime(), it returns
the number of milliseconds since January 1, 1970, 00:00:00 GMT represented by this Date object
One solution is to tell your SimpleDateFormat object to assume that all strings it parses are in GMT, rather than in the local time zone. Try adding this line after you initialize dt, but before calling dt.parse(...):
dt.setTimeZone(TimeZone.getTimeZone("GMT"));
This is quite easy to do with the new java.time API in Java 8 or with the JODA Time library:
import java.time.Duration;
import java.time.LocalTime;
public class TimeDiff {
public static void main(String[] args) {
LocalTime start = LocalTime.parse("05:53");
LocalTime end = LocalTime.parse("17:57");
// find the duration between the start and end times
Duration duration = Duration.between(start, end);
// add half the duration to the start time to find the midpoint
LocalTime midPoint = start.plus(duration.dividedBy(2));
System.out.println(midPoint);
}
}
Output:
11:55
By using LocalTime objects, you avoid any problems with time zones.
I think the problem is the types "long" and "int" in your code ;when we divide with 2 ( long timdedifferencemillis )the result must be "double".

Java Time API - A better way to get total elapsed time

This is my first oportunity to play with the "new" java.time package from Java 8.
I need to get the total elapsed time, something like:
1 day, 2h:3m:4s 5ms
I know that have 2 TemporalAmount implementations for intervals:
- Period for years, months and days
- Duration for hours, minutes, seconds, milliseconds and nanoseconds
There's a way to mix these two or something more straightforward than "do math"?
That was the best I could do until now:
(Updated with a new improved version)
LocalDateTime start = LocalDateTime.now();
// Forcing a long time execution to measure
LocalDateTime end = start
.plusDays(1)
.plusHours(2)
.plusMinutes(3)
.plusSeconds(4)
.plusNanos(5000);
LocalDateTime elapsed = end
.minusDays(start.getDayOfYear())
.minusHours(start.getHour())
.minusMinutes(start.getMinute())
.minusSeconds(start.getSecond())
.minusNanos(start.getNano());
Period period = Period.between(start.toLocalDate(), end.toLocalDate());
long days = period.getDays();
long hours = elapsed.getHour();
long minutes = elapsed.getMinute();
long seconds = elapsed.getSecond();
long milliseconds = elapsed.getNano() / 1000;
StringBuilder msg = new StringBuilder();
msg.append(seconds);
msg.append("s ");
msg.append(milliseconds);
msg.append("ms");
if(minutes > 0) {
msg.insert(0, "m:");
msg.insert(0, minutes);
}
if(hours > 0) {
msg.insert(0, "h:");
msg.insert(0, hours);
}
if(days > 0) {
msg.insert(0, days == 1 ? " day, " : " days, ");
msg.insert(0, days);
}
System.out.println(msg.toString());
Thanks for your time =)
Seems like you need the PeriodFormatter from JodaTime. See below links:
How to format a duration in java? (e.g format H:MM:SS)
Formatting a Duration in Java 8 / jsr310
Given these two, I suggest using JodaTime for Duration.

Time difference in seconds gives me wrong answers

I have two date strings and I want to know how many seconds difference there is between them.
2014-05-19 16:37:36:690 // formattedDate
2014-05-19 19:38:00:000 // expString
I use the following code:
SimpleDateFormat sdf = new SimpleDateFormat("yyy-MM-dd HH:mm:ss:SSS");
Date d1 = null;
Date d2 = null;
d1 = sdf.parse(expString);
d2 = sdf.parse(formattedDate);
long diff = d1.getTime() - d2.getTime();
long exp = diff / 1000 % 60;
In this particular example exp is 23. What is the problem here?
.getTime() returns the time in milliseconds since January 1, 1970, 00:00:00 GMT. So diff has the time in milliseconds between the two dates.
long diff = d1.getTime() - d2.getTime();
// diff = 10882310
You user integer division to get to seconds, which drops the extra milliseconds.
long temp = diff / 1000;
// temp = 10823
Then you modulus by 60, which gets you seconds and ignores seconds that were attributed to minutes.
long exp = temp % 60;
// exp = 23
If you want the total time in seconds between the two dates, you don't want to do that last operation.
Don't use modulus division! Just use plain division:
long diff = d1.getTime() - d2.getTime();
long exp = diff / 1000;
Better yet, use the TimeUnit enum from the JDK:
long exp = TimeUnit.MILLISECONDS.toSeconds(d1.getTime() - d2.getTime());
Joda-Time offers a Seconds class to just what you want.
The Joda-Time library also has classes to represent spans of time: Duration, Interval, and Period. You don’t strictly need them for this specific question, but they will be handy for related work.
Below is some untested code off the top of my head.
For simplicity, convert your strings to strict ISO 8601 format. Replace the SPACE with a T.
String inputStart = "…".replace( " ", "T" );
// same for stop
Create date-time objects. Explicitly assign a time zone by which to parse those strings. Are that UTC?
DateTime startDateTime = new DateTime( inputStart, DateTimeZone.UTC );
// repeat for stop
long secs = Seconds.secondsBetween( startDateTime, stopDateTime ).getSeconds();

Categories