Setting elapsed time and using toString - java

I want to create a Date object, set its elapsed time to 10000, 100000, 1000000, 10000000, 100000000, 1000000000, 10000000000, and 100000000000 milliseconds, and display the date and time using the toString() method.
But I am not sure how to create a for loop that manages with the increasing milliseconds value?
This is what I have so far:
public class Date {
public static void main(String[] args) {
long i = 0;
java.util.Date date = new java.util.Date(i);
date.setTime(i);
for (i = 1000; i < 100000000000L; i *= 10) {
System.out.println("Time elapsed: " + i + " milliseconds");
}
System.out.println("Date and time: " + date.toString());
}
}

Just put your date and toString into the for loop
long i = 0;
java.util.Date date = new java.util.Date(i);
for (i = 1000; i < 100000000000L; i *= 10) {
date.setTime(i);
System.out.println("Time elapsed: " + i + " milliseconds");
System.out.println("Date and time: " + date.toString());
}
}

import java.util.Date; // 1
class FoobarTimeMachine {
public static void main(String[] args) {
Date date; // 2
for(long i = 1000l; i <= 100000000000l; i *= 10) { // 3
System.out.println("Time elapsed since epoch: " + i + " milliseconds");
date = new Date(i); // 4
System.out.println("Corresponding date: " + date); // 5
}
}
}
Comments:
We're importing java.util.Date so we can use it later as Date.
We're not initialising the date right now, it's not needed.
With <= so we can reach 100 000 000 000.
Here we are initialising the date.
someString + someObject => someString + someObject.toString()

you can do as :
public static void main(String[] args) {
long i = 0;
Date d=new Date(i);
for (i = 1000; i < 100000000000L; i *= 10) {
System.out.println("Time elapsed: " + i + " milliseconds");
d.setTime(i);
System.out.println("Date and time: " + d.toString());
}
}

Related

Getting average from a random duration

I'm trying to print the maximum, minimum and average of the duration at the end of this code but i'm not too sure how to store the random duration in a specific array to display it after at the end. Below is the code:
public void test(){
int max;
int average;
int min;
long duration=2;
try
{ System.out.println("Bus Needs Cleaning" + "\n");
Thread.sleep(1000);
System.out.println("Bus getting cleaned");
Thread.sleep(1000);
duration = (long)(Math.random()*20);
TimeUnit.SECONDS.sleep(duration);
}
catch(InterruptedException iex)
{
}
System.out.println("Cleaner completed cleaning in" + duration + "Seconds");
System.out.println("Bus Leaves");
System.out.println("Average Waiting Time: " + average + " | Maximum: "+ max + " | Minimum" + min +"\n");
}
Any help would be much appreciated thanks!
EDIT: There are 5 buses coming in and going out and displaying different durations and they all go through the cleaning phase
please try this one. as far as I understood
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;
public class BusRandom {
public static void main(String[] args) {
new BusRandom().test();
}
public void test() {
long max = 0;
double average = 0;
long min = Long.MAX_VALUE;
int totalBuses=5;//change accordinly
List<Long> randomList = new ArrayList<>();
long duration = 2;
try {
for (int i = 0; i <totalBuses; i++) {
System.out.println("Bus Needs Cleaning" + "\n");
Thread.sleep(1000);
System.out.println("Bus getting cleaned");
Thread.sleep(1000);
duration = (long) (Math.random() * 20);
randomList.add(duration);
TimeUnit.SECONDS.sleep(duration);
System.out.println("Cleaner completed cleaning in" + duration + "Seconds");
System.out.println("Bus Leaves");
max=max>duration?max:duration;
min=min<duration?min:duration;
}
} catch (InterruptedException iex) {
}
double sum=0;
for(long l:randomList){
sum+=l;
}
average=(double) (sum/randomList.size());
System.out.println("Average Waiting Time: " + average + " | Maximum: " + max + " | Minimum" + min + "\n");
}
}

How do I get the military time difference to read correctly?

I am trying to write a program in which the console tells a person the difference between two times WITHOUT IF STATEMENTS, in "military time" or 24 hr time. So far, I have:
import java.util.Scanner;
public class MilTimeDiff {
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
System.out.print("Enter the first time: ");
String time1 = s.next();
System.out.print("Enter the second time: ");
String time2 = s.next();
String tm1 = String.format("%02d", Integer.parseInt(time1));
String tm2 = String.format("%02d", Integer.parseInt(time2));
int t1 = Integer.parseInt(tm1);
int t2 = Integer.parseInt(tm2);
int difference = t2 - t1;
while (t1 < t2) {
String tmDif = Integer.toString(difference);
System.out.println("The difference between times is " + tmDif.substring(0, 1) + " hours " +
tmDif.substring(1) + " minutes.");
break;
}
}
}
But I have two issues: one: if I make time one 0800, and time two 1700, it gives me the correct 9 hours. But if the difference is 10 hours or more, it gives 1 hour and a lot of minutes. I thought using the String.format method would help, but it doesn't do anything.
two: I'm not sure how to approach a situation where time 1 is later than time 2.
Thanks!
You can try below code which will give Time difference in military format :
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
System.out.print("Enter the first time: ");
String time1 = s.next();
System.out.print("Enter the second time: ");
String time2 = s.next();
String tm1 = String.format("%02d", Integer.parseInt(time1));
String tm2 = String.format("%02d", Integer.parseInt(time2));
String hrs1 = time1.substring(0, 2);
String min1 = time1.substring(2, 4);
String hrs2 = time2.substring(0, 2);
String min2 = time2.substring(2, 4);
// int difference = t2 - t1;
if (Integer.parseInt(time1) < Integer.parseInt(time2)) {
int minDiff = Integer.parseInt(min2) - Integer.parseInt(min1);
int hrsDiff = Integer.parseInt(hrs2) - Integer.parseInt(hrs1);
if (minDiff < 0) {
minDiff += 60;
hrsDiff--;
}
System.out.println("The difference between times is " + hrsDiff + " hours " + minDiff + " minutes.");
} else {
int minDiff = Integer.parseInt(min1) - Integer.parseInt(min2);
int hrsDiff = Integer.parseInt(hrs1) - Integer.parseInt(hrs2);
if (minDiff < 0) {
minDiff += 60;
hrsDiff--;
}
System.out.println("The difference between times is " + hrsDiff + " hours " + minDiff + " minutes.");
}
}

Calculate how long has passed Date java

I have a function:
public String getTimePast(Date d) {
//insertcodehere
}
That takes in a Date of a message and must return how much time has past based on the current time in specific format. For example if it has just been posted it will say "Now"
If it has been 4 minutes it will say "4min"
If it has been 23hrs it will say "23hrs"
Etc
Below is how I tried to do it with no luck! How am I able to do this? Thank you!
public String getTimePast(Date d) {
Calendar c = Calendar.getInstance();
int hr = c.get(Calendar.HOUR_OF_DAY);
int min = c.get(Calendar.MINUTE);
int day = c.get(Calendar.DAY_OF_MONTH);
int month = c.get(Calendar.MONTH);
int year = c.get(Calendar.YEAR);
if (year == d.getYear()) {
if (month == d.getMonth()) {
if (day == d.getDay()) {
if (hr == d.getHours()) {
if (min == d.getMinutes()) {
return "Now";
} else {
return min - d.getMinutes() + "m";
}
} else {
return hr - d.getHours() + "hr";
}
} else {
return day - d.getDay() + "d";
}
} else {
return month - d.getMonth() + "m";
}
} else {
return year - d.getYear() + "y";
}
}
How about using another Calendar Object as simply finding the difference
Calendar now = Calendar.getInstance();
Calendar start = Calendar.getInstance();
start.setTime (d);
long milliseconds1 = start.getTimeInMillis();
long milliseconds2 = now.getTimeInMillis();
long diff = milliseconds2 - milliseconds1;
long diffSeconds = diff / 1000;
long diffMinutes = diff / (60 * 1000);
long diffHours = diff / (60 * 60 * 1000);
long diffDays = diff / (24 * 60 * 60 * 1000);
System.out.println("\nThe Date Different Example");
System.out.println("Time in milliseconds: " + diff
+ " milliseconds.");
System.out.println("Time in seconds: " + diffSeconds
+ " seconds.");
System.out.println("Time in minutes: " + diffMinutes
+ " minutes.");
System.out.println("Time in hours: " + diffHours
+ " hours.");
System.out.println("Time in days: " + diffDays
+ " days.");
}
see http://www.roseindia.net/java/beginners/DateDifferent.shtml
You can use java.util.concurrent.TimeUnit
long diff = c.getTimeInMillis() - d.getTime();
long minutes = TimeUnit.MILLISECONDS.toMinutes(diff);
long hours = TimeUnit.MILLISECONDS.toHours(diff);
//(...)
and them check for values, like:
if (minutes > 60) {
if (hours > 24) {
// print days
} else {
// print hours
}
} else {
// print minutes
}
The easiest and most correct way to do this in Android is to use one of the functions in DateUtils, such as one of the variants of getRelativeTimeSpanString(). Which one to use is up to your requirements. This should be preferred because it will format the string according to the current locale, so it should work in any language supported by the device.

Java timeformat and time duration

Output I need is this:
Time in: 07:00 AM
Time out: 11:30 PM
Time duration: 16 hours and 30 minutes
User needs to enter in time in and time out, How do I do it? I searched and it seems that I need DateFormat hh:mm: a but I don't know how to use it. Help please. thanks.
DateFormat dateFormat = new SimpleDateFormat("hh:mm a");
long timeIn = dateFormat.parse("07:00 AM").getTime();
long timeOut = dateFormat.parse("11:30 PM").getTime();
long duration = (timeOut - timeIn) / 1000 / 60; // in minutes
long hours = duration / 60;
long minutes = duration % 60;
System.out.println("Time duration: " + hours + " hours and " + minutes + " minutes");
Prints:
Time duration: 16 hours and 30 minutes
Hi you can try something like this
public String timeDifference(String timeIn,String timeOut){
DateFormat dateFormat=new SimpleDateFormat("hh:mm a");
String result;
Date d=dateFormat.parse("08:14 AM"); //First input time in
Date d1=dateFormat.parse("09:00 PM"); //second input time out
long min=TimeUnit.MINUTES.convert(d1.getTime()-d.getTime(),TimeUnit.MILLISECONDS);
System.out.println(min);
if(min>=60){
long hrs=min/60;
result=String.valueOf(min/60)+" hours "+String.valueOf(min%60)+" minutes";
}
else
result=min+" minutes";
System.out.println(result);
return result;
}
You can trying something like this:
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
public class TimeTracker {
static Date getTimeIn() {
//There you must to use your specific Time In getting from user
//It's just example
Calendar calendarIn = Calendar.getInstance();
calendarIn.set(Calendar.HOUR_OF_DAY, 7);
calendarIn.set(Calendar.MINUTE, 00);
calendarIn.set(Calendar.SECOND, 0);
calendarIn.set(Calendar.MILLISECOND, 0 );
return calendarIn.getTime();
}
static Date getTimeOut() {
//There you must to use your specific Time In getting from user
//It's just example
Calendar calendarOut = Calendar.getInstance();
calendarOut.set(Calendar.HOUR_OF_DAY, 23);
calendarOut.set(Calendar.MINUTE, 30);
calendarOut.set(Calendar.SECOND, 0);
calendarOut.set(Calendar.MILLISECOND, 0);
return calendarOut.getTime();
}
public static void main(String[] args) throws InterruptedException {
DateFormat formatterTime = new SimpleDateFormat("hh:mm a");
long timeDuration = getTimeOut().getTime() - getTimeIn().getTime();
System.out.println("Time in: " + formatterTime.format(getTimeIn()));
System.out.println("Time out: " + formatterTime.format(getTimeOut()));
System.out.println("Time duration: " +
((timeDuration / (1000*60*60)) % 24)
+ " hours and " +
((timeDuration / (1000*60)) % 60) + " minutes");
}
}
Output is:
Time in: 07:00 AM
Time out: 11:30 PM
Time duration: 16 hours and 30 minutes

Java: convert seconds into day, hour, minute and seconds using TimeUnit

I am using TimeStamp class to convert seconds into Day,Hours,Minutes,Seconds. I used following code
public static void calculateTime(long seconds) {
int day = (int)TimeUnit.SECONDS.toDays(seconds);
long hours = TimeUnit.SECONDS.toHours(seconds) - TimeUnit.SECONDS.toHours(TimeUnit.SECONDS.toDays(seconds));
long minute = TimeUnit.SECONDS.toMinutes(seconds) - TimeUnit.SECONDS.toMinutes(TimeUnit.SECONDS.toHours(seconds));
long second = TimeUnit.SECONDS.toSeconds(seconds) - TimeUnit.SECONDS.toSeconds(TimeUnit.SECONDS.toMinutes(seconds));
System.out.println("Day " + day + " Hour " + hours + " Minute " + minute + " Seconds " + second);
}
But I am not getting right result.
For example when I called this method as calculateTime(3600) it gives me the result as Day 0 Hour 1 Minute 60 Seconds 3540 instead of Day 0 Hour 1 Minute 0 Seconds 0.
What is the wrong with my logic? Please help me.
It should be like
int day = (int)TimeUnit.SECONDS.toDays(seconds);
long hours = TimeUnit.SECONDS.toHours(seconds) - (day *24);
long minute = TimeUnit.SECONDS.toMinutes(seconds) - (TimeUnit.SECONDS.toHours(seconds)* 60);
long second = TimeUnit.SECONDS.toSeconds(seconds) - (TimeUnit.SECONDS.toMinutes(seconds) *60);
EDIT
Explanation:
Day calculation is correct, it does not require explanation.
TimeUnit.SECONDS.toHours(seconds) will give you direct conversion from seconds to hours without consideration for days you have already calculated. Minus the hours for days you already got i.e, day*24. You now got remaining hours.
Same for minute and second. You need to minus the already got hour and minutes respectively.
You can do like this to only use TimeUnit:
public static void calculateTime(long seconds) {
int day = (int) TimeUnit.SECONDS.toDays(seconds);
long hours = TimeUnit.SECONDS.toHours(seconds) -
TimeUnit.DAYS.toHours(day);
long minute = TimeUnit.SECONDS.toMinutes(seconds) -
TimeUnit.DAYS.toMinutes(day) -
TimeUnit.HOURS.toMinutes(hours);
long second = TimeUnit.SECONDS.toSeconds(seconds) -
TimeUnit.DAYS.toSeconds(day) -
TimeUnit.HOURS.toSeconds(hours) -
TimeUnit.MINUTES.toSeconds(minute);
System.out.println("Day " + day + " Hour " + hours + " Minute " + minute + " Seconds " + second);
}
or the slightly shorter but maybe not as intuitive
public static void calculateTime(long seconds) {
int day = (int) TimeUnit.SECONDS.toDays(seconds);
long hours = TimeUnit.SECONDS.toHours(seconds) -
TimeUnit.DAYS.toHours(day);
long minute = TimeUnit.SECONDS.toMinutes(seconds) -
TimeUnit.HOURS.toMinutes(TimeUnit.SECONDS.toHours(seconds));
long second = TimeUnit.SECONDS.toSeconds(seconds) -
TimeUnit.MINUTES.toSeconds(TimeUnit.SECONDS.toMinutes(seconds));
System.out.println("Day " + day + " Hour " + hours + " Minute " + minute + " Seconds " + second);
}
Simple method:
public static void calculateTime(long seconds) {
long sec = seconds % 60;
long minutes = seconds % 3600 / 60;
long hours = seconds % 86400 / 3600;
long days = seconds / 86400;
System.out.println("Day " + days + " Hour " + hours + " Minute " + minutes + " Seconds " + sec);
}
Here is a code i created : (For 3600 seconds it shows "Days:0 Hours:1 Minutes:0 Seconds:0")
public class TimeConvert
{
public static void main(String[] args)
{
int fsec,d,h,m,s,temp=0,i;
fsec=3600;
//For Days
if(fsec>=86400)
{
temp=fsec/86400;
d=temp;
for(i=1;i<=temp;i++)
{
fsec-=86400;
}
}
else
{
d=0;
}
//For Hours
if(fsec>=3600)
{
temp=fsec/3600;
h=temp;
for(i=1;i<=temp;i++)
{
fsec-=3600;
}
}
else
{
h=0;
}
//For Minutes
if(fsec>=60)
{
temp=fsec/60;
m=temp;
for(i=1;i<=temp;i++)
{
fsec-=60;
}
}
else
{
m=0;
}
//For Seconds
if(fsec>=1)
{
s=fsec;
}
else
{
s=0;
}
System.out.println("Days:"+d+" Hours:"+h+" Minutes:"+m+" Seconds:"+s);
}
}
Hope it answers your question.
Late but helpful
get time in the format 00:00:00
/**
* The time in format.
*
* in The Format of 00:00:00
*/
public String getTimeInFormat(long _SECONDS)
{
if(TimeUnit.SECONDS.toHours(_SECONDS)>0)
{
return String.format("%02d:%02d:%02d",
TimeUnit.SECONDS.toHours(_SECONDS),
TimeUnit.SECONDS.toMinutes(_SECONDS) -
TimeUnit.HOURS.toMinutes(TimeUnit.SECONDS.toHours(_SECONDS)),
TimeUnit.SECONDS.toSeconds(_SECONDS) -
TimeUnit.MINUTES.toSeconds(TimeUnit.SECONDS.toMinutes(_SECONDS)));
}
else {
return String.format("%02d:%02d",
TimeUnit.SECONDS.toMinutes(_SECONDS) -
TimeUnit.HOURS.toMinutes(TimeUnit.SECONDS.toHours(_SECONDS)),
TimeUnit.SECONDS.toSeconds(_SECONDS) -
TimeUnit.MINUTES.toSeconds(TimeUnit.SECONDS.toMinutes(_SECONDS)));
}
}
Try this
public static void calculateTime(long seconds) {
int day = (int)TimeUnit.SECONDS.toDays(seconds);
long hours = TimeUnit.SECONDS.toHours(seconds) ;
long tempSec = seconds - (TimeUnit.HOURS.toSeconds(hours) );
System.out.println("after hours calculation "+ tempSec);
long minute = TimeUnit.SECONDS.toMinutes(tempSec);
if(tempSec > TimeUnit.MINUTES.toSeconds(minute)){
tempSec = tempSec - (TimeUnit.MINUTES.toSeconds(minute) );
}else{
tempSec = TimeUnit.MINUTES.toSeconds(minute) - tempSec;
}
System.out.println("after min calculation "+ tempSec);
long second = TimeUnit.SECONDS.toSeconds(tempSec) ;
System.out.println("Day " + day + " Hour " + hours + " Minute " + minute + " Seconds " + second);
}
This is my code:
public static String secondsToString(TimeUnit greatestUnit, long sourceDuration, TimeUnit sourceUnit) {
int ordinal = greatestUnit.ordinal();
if(ordinal<=sourceUnit.ordinal())
return String.format("%02d", sourceDuration);
final long greatestDuration = greatestUnit.convert(sourceDuration, sourceUnit);
final long rest = sourceDuration - sourceUnit.convert(greatestDuration, greatestUnit);
return String.format("%02d:", greatestDuration) + secondsToString(TimeUnit.values()[--ordinal], rest, sourceUnit);
}
or by loop
public static String secondsToStringByLoop(TimeUnit greatestUnit, long sourceDuration, TimeUnit sourceUnit) {
final StringBuffer sb = new StringBuffer();
int ordinal = greatestUnit.ordinal();
while(true){
if(ordinal<=sourceUnit.ordinal()) {
sb.append(String.format("%02d", sourceDuration));
break;
}
final long greatestDuration = greatestUnit.convert(sourceDuration, sourceUnit);
// if(greatestDuration>0 || sb.length()>0)
sb.append(String.format("%02d:", greatestDuration));
sourceDuration -= sourceUnit.convert(greatestDuration, greatestUnit);
greatestUnit = TimeUnit.values()[--ordinal];
};
return sb.toString();
}
usage example:
String str = secondsToString(TimeUnit.DAYS, 1000, TimeUnit.SECONDS);
function returns: "00:00:16:40" (days:hours:minutes:seconds)
str = UnitsConverter.secondsToString(TimeUnit.DAYS, 1000, TimeUnit.MINUTES);
returns: "00:16:40" (days:hours:minutes)
str = UnitsConverter.secondsToString(TimeUnit.MINUTES, 1000, TimeUnit.SECONDS);
returns: "16:40" (minutes:seconds)
public static void timeCalculator(){
Scanner input = new Scanner(System.in);
System.out.print("Enter length of time in seconds: ");
int n = input.nextInt();
int nDay = n/86400;
int nHours = (n%86400)/3600;
int nMin = ((n%86400)%3600) /60;
int nSec =(((n%86400)%3600)%60);
System.out.println();
System.out.print("That is "+ nDay+ " day(s),"+nHours+" hour(s), "+nMin+" minute(s), and "+nSec+" second(s). ");
}

Categories