time is not showing perfectly, I am trying to show my system timings.
Also I am not able to set these
int minut = calendar.getTime().getMinutes();
int hours = calendar.getTime().getHours();
int sec = calendar.getTime().getSeconds();
It gave error:
The method getSeconds() from the type Date is depreciated.
The method getHours() from the type Date is depreciated.
The method getMinutes() from the type Date is depreciated.
Calendar cal = Calendar.getInstance(TimeZone.getDefault());
int hours = cal.getTime();
int minut = cal.getTime();
hours = hours * 30 + minut / 2;
minut = minut * 6;
int sec = cal.getTime();
minut = minut +sec/10;
sec = sec * 6;
hr.setRotate(hours);
minute.setRotate(minut);
second.setRotate(sec);
Scene sc = new Scene(pane);
ps.setScene(sc);
It give me the time for example if my system time is 10:25 it shows 09:25
Your code makes not much sense to me but get keep in mind that Calender.getTimeInMillis() or Date.getTime() return the time in UTC - regardless the timezone you set on the calendar.
Please try below code, it will give you correct time:
Calendar now = Calendar.getInstance();
int hour = now.get(Calendar.HOUR_OF_DAY);
int minute = now.get(Calendar.MINUTE);
int second = now.get(Calendar.SECOND);
int millis = now.get(Calendar.MILLISECOND);
System.out.println(hour + ":" + minute + ":" + second + ":" + millis);
Related
I'm trying to make a countdown timer that will reset weekly (Mondays at 10am eastern). I've found something similar to what I'm looking for, but it doesn't reset itself; it goes into the negative. Can someone please help me get this working?
public static int SECONDS_IN_A_DAY = 24 * 60 * 60;
public String main(String[] args) {
Calendar now = Calendar.getInstance();
int year = now.get(Calendar.YEAR);
int month = now.get(Calendar.MONTH);
Calendar reset = Calendar.getInstance();
reset.setTime(new Date(0));
reset.set(Calendar.DAY_OF_WEEK, 1); //2
reset.set(Calendar.MONTH, month);
reset.set(Calendar.YEAR, year);
reset.set(Calendar.HOUR_OF_DAY, 0); //10
reset.set(Calendar.MINUTE, 33);
Calendar today = Calendar.getInstance();
long diff = reset.getTimeInMillis() - today.getTimeInMillis();
long diffSec = diff / 1000;
long days = diffSec / SECONDS_IN_A_DAY;
long secondsDay = diffSec % SECONDS_IN_A_DAY;
long seconds = secondsDay % 60;
long minutes = (secondsDay / 60) % 60;
long hours = (secondsDay / 3600);
if (diff < 0) {
reset.setTime(new Date(0));
reset.set(Calendar.DAY_OF_WEEK, 1); //2
reset.set(Calendar.MONTH, month);
reset.set(Calendar.YEAR, year);
reset.set(Calendar.HOUR_OF_DAY, 0); //10
reset.set(Calendar.MINUTE, 33);
}
return "Reset in: " + days + " days, " + hours + " hours, " + minutes + " minutes, and " + seconds + " seconds.";
}
public void onMessageReceived(MessageReceivedEvent e) {
if(e.getMessage().getRawContent().equalsIgnoreCase(";reset")) {
e.getChannel().sendMessage(main(null)).queue();
}
}
I cant figure out how to make this reset once it reaches reset time. Any help very much appreciated. I haven't coded in 5+ years.
Below is screenshot of the output if the time has passed.
https://puu.sh/w3odJ/009663b380.png
Thanks!
UPDATE: I'm finding the best method for this is to use reset.add to add 7 days to the reset calendar. Can't get the proper conditions to be met to achieve this yet though. I've tried reset.compareTo(today) as well as some other combinations which aren't working, but it's progress.
How can I calculate the difference between two dates and show it in the format hours:minutes:seconds?
Example:
StartTime : 2016-12-20T04:30
EndTime : 2016-12-22T05:00
The output should be "48hours 30minutes 0 seconds".
This is what I've tried:
Long diff = (endDate.get time() -startDate.gettime())/1000;
Log.d("App","difference in hour is"+diff/1000/60/60);
Mins = diff/1000/60;
Seconds = diff/1000;
Using this code I'm getting hours as a correct value. But the minute and seconds values are not getting their proper values.
Try this function:-
//1 minute = 60 seconds
//1 hour = 60 x 60 = 3600
//1 day = 3600 x 24 = 86400
public void printDifference(Date startDate, Date endDate){
//milliseconds
long different = endDate.getTime() - startDate.getTime();
System.out.println("startDate : " + startDate);
System.out.println("endDate : "+ endDate);
System.out.println("different : " + different);
long secondsInMilli = 1000;
long minutesInMilli = secondsInMilli * 60;
long hoursInMilli = minutesInMilli * 60;
long daysInMilli = hoursInMilli * 24;
//long elapsedDays = different / daysInMilli;
//different = different % daysInMilli;
long elapsedHours = different / hoursInMilli;
different = different % hoursInMilli;
long elapsedMinutes = different / minutesInMilli;
different = different % minutesInMilli;
long elapsedSeconds = different / secondsInMilli;
System.out.printf(
"%d hours, %d minutes, %d seconds%n",
elapsedHours, elapsedMinutes, elapsedSeconds);
}
Try
1. Add following methods first, then use parseDate.
Date startDate = parseDate("2016-12-20T04:30");
Date endDate = parseDate("2016-12-22T05:00");
2. Calculate difference b/w these two
long differenceInMillis = endDate.getTime() - startDate.getTime();
3. Use formatElapsedTime method to formatted difference
String formattedText = formatElapsedTime(differenceInMillis/1000); //divide by 1000 to get seconds from milliseconds
//Result will be 48hours 30minutes 0 seconds
public static Date parseDate (String strDate) {
DateFormat dateFormat = new SimpleDateFormat ("yyyy-MM-dd'T'HH:mm");
Date date1 = null;
try {
date1 = dateFormat.parse (strDate);
}
catch (ParseException e) {
e.printStackTrace ();
}
return date1;
}
public static String formatElapsedTime (long seconds) {
long hours = TimeUnit.SECONDS.toHours(seconds);
seconds -= TimeUnit.HOURS.toSeconds (hours);
long minutes = TimeUnit.SECONDS.toMinutes (seconds);
seconds -= TimeUnit.MINUTES.toSeconds (minutes);
return String.format ("%dhr:%dmin:%dsec", hours, minutes, seconds);
}
import java.util.Calendar;
public class DateDifferenceExample {
public static void main(String[] args) {
// Creates two calendars instances
Calendar cal1 = Calendar.getInstance();
Calendar cal2 = Calendar.getInstance();
// Set the date for both of the calendar instance
cal1.set(2006, Calendar.DECEMBER, 30);
cal2.set(2007, Calendar.MAY, 3);
// Get the represented date in milliseconds
long millis1 = cal1.getTimeInMillis();
long millis2 = cal2.getTimeInMillis();
// Calculate difference in milliseconds
long diff = millis2 - millis1;
// Calculate difference in seconds
long diffSeconds = diff / 1000;
// Calculate difference in minutes
long diffMinutes = diff / (60 * 1000);
// Calculate difference in hours
long diffHours = diff / (60 * 60 * 1000);
// Calculate difference in days
long diffDays = diff / (24 * 60 * 60 * 1000);
System.out.println("In milliseconds: " + diff + " milliseconds.");
System.out.println("In seconds: " + diffSeconds + " seconds.");
System.out.println("In minutes: " + diffMinutes + " minutes.");
System.out.println("In hours: " + diffHours + " hours.");
System.out.println("In days: " + diffDays + " days.");
}
}
New answer to an old question using a newer API: java.time
You can write a method that actually accepts the datetimes as Strings along with a time zone and then calculates the difference by means of a class designed for such purpose: java.time.Duration
Here's a code example:
public static String getDifference(String firstDt, String secondDt, String zone) {
// create the zone for the calculation just to respect daylight saving time
ZoneId zoneId = ZoneId.of(zone);
// then parse the datetimes passed and add the time zone
ZonedDateTime firstZdt = ZonedDateTime.of(
LocalDateTime.parse(firstDt), zoneId
);
ZonedDateTime secondZdt = ZonedDateTime.of(
LocalDateTime.parse(secondDt), zoneId
);
// calculate the duration between the two datetimes
Duration duration;
/*
* the JavaDocs of Duration tell us the following:
*
* "The result of this method can be a negative period
* if the end is before the start.".
*
* So we need to make sure the older datetime will be
* the "start" in the method "between(start, end)"
*/
if (firstZdt.isAfter(secondZdt)) {
duration = Duration.between(secondZdt, firstZdt);
} else {
duration = Duration.between(firstZdt, secondZdt);
}
// store the amount of full hours the duration has
long hoursBetween;
hoursBetween = duration.toHours();
// calculate the minutes left from the full duration in minutes
long minutesBetween;
minutesBetween = duration.toMinutes() - (hoursBetween * 60);
// calculate the seconds left from the full duration in seconds
long secondsBetween;
secondsBetween = duration.getSeconds() - (duration.toMinutes() * 60);
// build the result String, take care of possibly missing leading zeros
StringBuilder resultBuilder = new StringBuilder();
resultBuilder.append(hoursBetween).append(" hours ");
if (minutesBetween < 10 && minutesBetween > 0)
resultBuilder.append("0");
resultBuilder.append(minutesBetween).append(" minutes ");
if (secondsBetween < 10 && secondsBetween > 0)
resultBuilder.append("0");
resultBuilder.append(secondsBetween).append(" seconds");
return resultBuilder.toString();
}
If you use it in a main...
public static void main(String[] args) {
String timeDiff = getDifference("2016-12-20T04:30", "2016-12-22T05:00", "UTC");
System.out.println(timeDiff);
}
... you will get the following output:
48 hours 30 minutes 0 seconds
The code above is the one to be used in Java 8, later on, Duration got the methods toHoursPart(), toMinutesPart() and toSecondsPart() which actually do the necessary calculation internally.
The code that would change (tried with Java 11):
// store the amount of full hours the duration has
long hoursBetween;
hoursBetween = duration.toHoursPart();
// calculate the minutes left from the full duration in minutes
long minutesBetween;
minutesBetween = duration.toMinutesPart();
// calculate the seconds left from the full duration in seconds
long secondsBetween;
secondsBetween = duration.toSecondsPart();
I'm currently trying to convert a long to a remaining time. I have got a
long remaining = XXXX
The long are the milliseconds to a certain date. For example: 3,600,000 should result in int weeks = 0, days = 0, hours = 1, minutes = 0, seconds = 0
how can I convert this long so that I end up with 5 ints:
int weeks;
int days;
int hours;
int minutes;
int seconds;
Thank you in advance!
DirtyDev
First, I suggest defining the number of ms in a second, minute, hour, etc as constants
static final int SECOND = 1000; // no. of ms in a second
static final int MINUTE = SECOND * 60; // no. of ms in a minute
static final int HOUR = MINUTE * 60; // no. of ms in an hour
static final int DAY = HOUR * 24; // no. of ms in a day
static final int WEEK = DAY * 7; // no. of ms in a week
Then, you can use basic division (/) and modulus (%) operations to find what you need.
long remaining = XXXX;
int weeks = (int)( remaining / WEEK);
int days = (int)((remaining % WEEK) / DAY);
int hours = (int)((remaining % DAY) / HOUR);
int minutes = (int)((remaining % HOUR) / MINUTE);
int seconds = (int)((remaining % MINUTE) / SECOND);
Excuse me, I don’t want to criticize too much, still I gather from the other answers that it’s easy to either write code that is hard to read or code with typos that gives an incorrect result. DirtyDev, I am aware that you may not be allowed to use Duration, but for anyone else:
long remaining = 3_600_000;
Duration remainingTime = Duration.ofMillis(remaining);
long days = remainingTime.toDays();
remainingTime = remainingTime.minusDays(days);
long weeks = days / 7;
days %= 7; // or if you prefer, days = days % 7;
long hours = remainingTime.toHours();
remainingTime = remainingTime.minusHours(hours);
long minutes = remainingTime.toMinutes();
remainingTime = remainingTime.minusMinutes(minutes);
long seconds = remainingTime.getSeconds();
System.out.println("" + weeks + " weeks " + days + " days "
+ hours + " hours " + minutes + " minutes " + seconds + " seconds");
This prints:
0 weeks 0 days 1 hours 0 minutes 0 seconds
It’s not perfect, but I believe it’s both readable, correct and robust. Duration was meant for times from hours down to nanoseconds, so we still have to do the weeks “by hand”.
Happy New Year.
This should do what you want.
long inputTimeInMilliseconds = 93800000;
long milliseconds = inputTimeInMilliseconds % 1000;
long seconds = (inputTimeInMilliseconds / 1000) % 60 ;
long minutes = ((inputTimeInMilliseconds / (1000*60)) % 60);
long hours = ((inputTimeInMilliseconds / (1000*60*60)) % 24);
long days = ((inputTimeInMilliseconds / (1000*60*60*24)) % 7);
long weeks = (inputTimeInMilliseconds / (1000*60*60*24*7));
String remainingTime = "time:"+weeks+":"+days+":"+ hours+":"+minutes+":"+seconds+":"+milliseconds;
System.out.println(remainingTime);
How can I add/subtract with time in Java? For example, I'm writing a program that when you input your bedtime, it then adds 90 minutes (the length of 1 sleep cycle) to tell you the ideal wake up time.
Scanner input;
input = new Scanner (System.in);
int wakeup0;
int wakeup1;
int wakeup2;
int wakeup3;
int wakeup4;
int wakeup5;
System.out.println("When will you be going to bed?");
int gotobed = Integer.parseInt(input.nextLine());
wakeup0 = gotobed + 90;
wakeup1 = wakeup0 + 90;
wakeup2 = wakeup1 + 90;
wakeup3 = wakeup2 + 90;
wakeup4 = wakeup3 + 90;
wakeup5 = wakeup4 + 90;
System.out.println("You should set your alarm for: "+wakeup0+" "+wakeup1+" "+wakeup2+" "+wakeup3+" "+wakeup4+" or "+wakeup5);
How do I make it so that when I add 90 to 915 it gives me 1045 rather than 1095?
Calculate everything in milliseconds. That might at first seem inconvenient but the math is quite straightforward.
When inputting the bedtime, you need to decide how the user will do this. Will it be hours and minutes. Will there be AM/PM or 24 hour clock. And what time zone will you be considering. All of this is done with a Calendar or DateFormat class and it will give you a single long value with the specified time in it.
After that, adding a time offset is easy.
SimpleDateFormat df = new SimpleDateFormat("HHmm");
long bedttime = df.parse(inputValue).getTime();
long wakeup1 = bedttime + (90 * 60 * 1000); //90 minutes in milliseconds.
long wakeup2 = wakeup1 + (90 * 60 * 1000); //90 minutes in milliseconds.
long wakeup3 = wakeup2 + (90 * 60 * 1000); //90 minutes in milliseconds.
long wakeup4 = wakeup3 + (90 * 60 * 1000); //90 minutes in milliseconds.
long wakeup5 = wakeup4 + (90 * 60 * 1000); //90 minutes in milliseconds.
System.out.println("The first wakeup time is "+df.format(new Date(wakeup1)));
Each long value holds the time that the alarm should go off. Use the formatter again to generate a user friendly representation of that time value.
Firstly, there is no direct conversion from a 4 digit number to a time.
So you will need to use Calendar
From this you can get the current date/time Calendar rightNow = Calendar.getInstance();
Then you can use the add method to add your 90 minutes see http://docs.oracle.com/javase/7/docs/api/java/util/Calendar.html#add(int, int)
May not be the exact reply to your question. You should probably use Calendar and SimpleDateFormat in this case like below.
SimpleDateFormat df = new SimpleDateFormat("HHmm");
System.out.println("When will you be going to bed?");
String gotobed = input.nextLine();
Date date = df.parse(gotobed);
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
calendar.add(Calendar.MINUTE, 90);
String wakeup0 = df.format(calendar.getTime());
calendar.add(Calendar.MINUTE, 90);
String wakeup1 = df.format(calendar.getTime());
calendar.add(Calendar.MINUTE, 90);
String wakeup2 = df.format(calendar.getTime());
calendar.add(Calendar.MINUTE, 90);
String wakeup3 = df.format(calendar.getTime());
calendar.add(Calendar.MINUTE, 90);
String wakeup4 = df.format(calendar.getTime());
calendar.add(Calendar.MINUTE, 90);
String wakeup5 = df.format(calendar.getTime());
System.out.println("You should set your alarm for: " + wakeup0 + " "
+ wakeup1 + " " + wakeup2 + " " + wakeup3 + " " + wakeup4
+ " or " + wakeup5);
For Input 0900 the output will be,
When will you be going to bed?
0900
You should set your alarm for: 1030 1200 1330 1500 1630 or 1800
This will be easier if you separate the hours and minutes given that an hour is made up of 60 and not 100 minutes. Ask the user to input their time as "HH:MM" and parse it using split(":") to get the hours and minutes separately:
System.out.println("When will you be going to bed?");
String rawBedtime = input.nextLine();
String[] gotobed = rawBedtime.split(":");
int minutes = Integer.parseInt(gotobed[0]);
int hours = Integer.parseInt(gotobed[1]);
To get the number of hours and minutes to add:
int additionalHours = 90/60;
int additionalMinutes = 90%60;
However, I would probably Java's Calendar or Date classes. They will take care of a lot of the nitty-gritty for you.
I want to calculate the difference between a certain date and the current time.
int month = 9;
int day = 17;
int year = 2013;
Calendar date = new GregorianCalendar(year, month, day);
int miliseconds= (int) (System.currentTimeMillis() - calendar.getTimeInMillis());
System.out.println(msToString(second));
String msToString(int ms) {
return (new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS")).format(new Date(ms));
}
the output is
13091-13091/? D/GTA: 1970-01-08 15:00:20.287
I want to get the amount of days, hours,minutes and seconds remaining.
What do I wrong?
you could try something like the following method
import java.util.Calendar;
import java.util.GregorianCalendar;
public class TimeToGoCalculator {
/**
* #param args
*/
public static void main(String[] args) {
int month = 8;
int day = 19;
int year = 2013;
Calendar calendar = new GregorianCalendar(year, month, day);
int timeToGo = (int) (calendar.getTimeInMillis() - System.currentTimeMillis())/1000;
System.out.println(secondsToString(timeToGo));
}
private static String secondsToString(int seconds) {
int days = seconds / 24 / 3600;
int hours = (seconds - (days * 24 * 3600 )) / 3600;
int minutes = (seconds - (days * 24 * 3600 + hours * 3600)) / 60;
seconds = (seconds - (days * 24 * 3600 + hours * 3600 + minutes * 60));
return "The remaining time is "+days+" days, "+hours+" hours, "+minutes+
" minutes, and "+seconds+" seconds.";
}
}
That should give you the output you're looking for.
Notice that, when creating the GregorianCalendar object, the month is 0-indexed, so September would be = 8.
Use Joda Time library
Period class can help.
int month = 9;
int day = 17;
int year = 2013;
int hour= 0;
int minute =0;
int second =0;
int millisecond = 0;
DateTime dt1 = new DateTime(); //now
DateTime dt2 = new DateTime(year, month, day, hour, minute, second, millisecond);
//assuming dt1 is before dt2:
Period period = new Period(dt1, dt2, PeriodType.dayTime());
/*
periodType.dayTime()):
Gets a type that defines all standard fields from days downwards.
days
hours
minutes
seconds
milliseconds
*/
PeriodFormatter periodFormatter = new PeriodFormatterBuilder()
.printZeroAlways()
.minimumPrintedDigits(2)
.appendDays().appendSuffix("days ")
.appendHours().appendSuffix("hours ")
.appendMinutes().appendSuffix("minutes ")
.appendSeconds().appendSuffix("seconds ");
.toFormatter();
System.out.println(periodFormatter.print(period));
Are you able to use external libraries? Then Joda Time can help you, especially the Period class.
It has a constructor for two time instants and gives you the difference between the time instants in years/months/days/hours/seconds/milliseconds.
Your second variable holds an amount of milliseconds between the two dates, not a new date. You need to do some calculation using these milliseconds to get an amount of days, for instance.
You could do something like this:
int minutes = second/1000/60; // millis to seconds, seconds to minutes
to get an amount of minutes, then convert to hours, and so on.