Initial time=22:00:00,final time=23:59:59.
If the current time is, let's say 23:00:00 then I will get the success message otherwise error message will be shown. And I am comparing this time with the system time.
My code:
//retrieving the system time in string format
SimpleDateFormat sdfDate = new SimpleDateFormat("HH:mm:ss");
Date date = new Date();
String s=sdfDate.format(date);
//Initial and final predefined time
String ten ="22:00:00";
String twelve ="23:59:59";
//comparing with the system time
try{
if(s.compareTo("twelve")<0 && s.compareTo("ten")>0 ){
out.print("success");
}else{
out.print("failed");
}
}catch(Exception l){
System.out.println(l.toString());
}
I tried to check it when the system time was 23:45:00. I also confirmed the time by printing out.print(""+s);. But I got the failed message. I don't know my loop is working or not.
What can I do to fix this?
If you're comparing hours, don't use strings, use a proper type.
In Java you have:
Java >= 8: java.time.LocalTime
Java <= 7: org.threeten.bp.LocalTime (from external lib: http://www.threeten.org/threetenbp/)
In both you can do:
LocalTime ten = LocalTime.parse("22:00:00");
LocalTime twelve = LocalTime.parse("23:59:59");
// current time
LocalTime now = LocalTime.now();
// compare
if (now.isBefore(twelve) && now.isAfter(ten)) {
// succcess
}
To get the current time, you could also use the now method with a timezone (example: LocalTime.now(ZoneId.of("America/New_York"))), if you need the time at some specific place (now() without arguments will use the JVM default timezone).
Transforming the strings to a type that represents the data you're working with is much more reliable. Also note that this API makes the code much easier and more readable, with meaningful methods names such as isAfter and isBefore.
Comparing strings might work, but using the proper types works even better.
Try this:
if(s.compareTo(twelve) < 0 && s.compareTo(ten) > 0)
By putting quotes around twelve and ten, you're comparing to the strings "twelve" and "ten", and not referencing the variables twelve and ten that you defined ealier in the program.
Related
Problem situation: I have an incredibly high number of records all marked with a timestamp. I'm looping through all of them to do this and that but I need to detect when the day has changed.
Right now for each loop I'm doing:
cal.setTimeInMillis(record.time);
int currentDay = cal.get(Calendar.DAY_OF_WEEK);
Is this as slow as I imagine it is when it's running hundreds of thousands of times?
I imagine I'm missing a really simple modulo answer or something.
Edit: Time zone does not matter, the information I'm collecting more resolves around a consumable report for someone. 24 hours per report is more accurate, so realistically I don't have to worry about whether or not that's 5am - 5am or 3pm - 3pm, just that I was able to gather 24H worth of info.
Thanks all
After Andy Turner’s time test I am not necessarily convinved that you need any optimized solution. In any case, timsmelik’s suggestion is pretty straightforward: convert the time when the day changes to a count of milliseconds since the epoch so you only need to compare long values. I don’t find that it hurts readability very badly. So here it is in code. I am using and warmly recommending java.time, the modern Java date and time API, if only for the conversion from hours to milliseconds and for printing the results. Even when such a conversion seems trivial, it’s always best to leave to the standard library to do it. It’s more self-explanatory and less error-prone, and it’s easier for the reader to convince oneself that it’s correct.
final long twentyfourHoursAsMillis = Duration.ofHours(24).toMillis();
// Times are already sorted descending (from newest to oldest)
long[] times = { 1_611_718_370_000L, 1_611_632_000_000L,
1_611_631_970_000L, 1_611_459_150_000L };
List<List<Long>> chunks = new ArrayList<>();
List<Long> currentChunk = new ArrayList<>();
// Process first time separately to get started
currentChunk.add(times[0]);
long timeOfNextChunk = times[0] - twentyfourHoursAsMillis;
// Process remaining times
for (int i = 1; i < times.length; i++) {
long currentTime = times[i];
if (currentTime <= timeOfNextChunk) {
chunks.add(currentChunk);
currentChunk = new ArrayList<>();
do {
timeOfNextChunk -= twentyfourHoursAsMillis;
} while (currentTime <= timeOfNextChunk);
}
currentChunk.add(currentTime);
}
// Save last chunk, why not?
chunks.add(currentChunk);
// Print result
for (List<Long> chunk : chunks) {
String chunkAsString = chunk.stream()
.map(Instant::ofEpochMilli)
.map(Instant::toString)
.collect(Collectors.joining(", "));
System.out.println(chunkAsString);
}
Output is:
2021-01-27T03:32:50Z, 2021-01-26T03:33:20Z
2021-01-26T03:32:50Z
2021-01-24T03:32:30Z
I am printing Instant objects. They always print in UTC. For your situation you may want to do otherwise if you need to print the times at all.
You should add a check of your assumption that the times come in sorted order.
I have taken your word for it and broken into chunks at 24 hours. 24 hours may not even mean 5am - 5am but could mean for instance from 5 AM EST on March 13 to 6 AM EDT on March 14 because summer time (DST) has begun in the meantime. If you prefer to split at the same clock hour, the code can be modified to do that.
I know it may seems easy but i'm really new on Java , So i need your help.
I want to use local time (Mill Seconds) to trigger an action, for example printing "Hello world".
More specific, Print "Hello world" at "13:10:30:300" . but i don't know what specific class should i use (Data,Local Time , etc) so i can compare it to Desired Time in a while loop.
I tried this, but it's not working on milliseconds.
import java.time.format.DateTimeFormatter;
DateTimeFormatter dtf = DateTimeFormatter.ofPattern("HH:mm:ss:ms");
LocalDateTime now = LocalDateTime.now();
LocalDateTime desire = 13:10:30.300;
while (now != desire ) {
LocalDateTime now = LocalDateTime.now();
}
System.out.println("Hello World!");
Do you have any suggestion please?
Your main problem is this: now != desire. This compares whether these objects are the same, not whether their contents are the same. To compare if the times are the same, you should use now.equals(desire).
Your second problem is that this this loop might become infinite if between 2 checks now becomes greater than desire.
Your third problem is that you are wasting CPU cycles constantly checking the time. You should calculate how many milliseconds your desired time is away and sleep until then. So something like: Thread.sleep(desireMillis - nowMillis)
I have a date supplied by the user and of course today's date.
I'm attempting to verify that the difference between the 2 days is at least 2 weeks. I've done this using standard libraries - but I'm attempting to do this using jodaTime and I'm having some difficulty.
// BAD CODE - doesn't work
// NOTE: getUserSuppliedDate() returns an instance of java.sql.Date
// Also assume that validation prior to this call has been run that
// validates that the userSuppliedDate comes AFTER today's date - not sure if
// that is relevant in the context I'm attempting to use these particular jodaTime APIs.
DateTime jodaStartDate = new DateTime(getUserSuppliedDate());
if (Days.daysBetween(jodaStartDate, DateTime.now()).isLessThan(Days.days(14))) {
System.out.println("Bad user. You have chosen...poorly.");
}
else {
System.out.println("Well done user. You have supplied wisely.");
}
// GOOD CODE ---- ? Help =)
Your code gives you the wrong result because the dates supplied to Days.daysBetween() are in the wrong order. Since you specified that the user supplied date comes after the current date, your approach will result in a negative number of days.
It will work correctly if you switch the order, putting the earliest date first.
Compare the following two:
DateTime jodaStartDate = new DateTime().withYear(2018)
.withMonthOfYear(7)
.withDayOfMonth(5); // 15 days from now
System.out.println(Days.daysBetween(jodaStartDate, DateTime.now())); // "P-15D"
System.out.println(Days.daysBetween(DateTime.now(), jodaStartDate)); // "P15D"
In the first case, -15 days will evaluate to less than 14 days.
Using weeks instead of days, you'd run into the same problem:
System.out.println(Weeks.weeksBetween(jodaStartDate, DateTime.now())); // "P-2W"
System.out.println(Weeks.weeksBetween(DateTime.now(), jodaStartDate)); // "P2W"
I looked at this question and my problem is similar but not exactly identical. I have many timestamps in problem and they are all in the form "yyyyMMddHHmmssSSS", so I am parsing the string as follow:
DateTimeFormatter.ofPattern("yyyyMMddHHmmssSSS").parse("20180301050630663")
which will output 2018-03-01T05:06:30.663 (I do not know what the "T" in the middle stands for and do not know how to get rid of it)
Problem is I only care about the timestamps that lies within the range of [09:15:00.000am -12:00:00.000pm] and [15:15:00.000pm -18:00:00.000pm] across all different dates (inclusive too, meaning that if the timestamp is exactly at 09:15:00.000, then it should return true too).
However, how should I tackle this problem because sometimes the dates could be different, i.e. it could be across different dates 2018-03-01T05:06:30.663, 2018-03-02T10:36:30.596,2018-03-11T05:06:30.663? Since the date and times always come together, shall I extract the time from the timestamp ? What is the best way to deal with this in this situation ? I am not too familiar with the datetime libraries in Java.
You were on the right track with DateTimeFormatter. Rather than use DateTimeFormatter.parse, you can pass this formatter to LocalTime.parse which will effectively discard the date portion of the timestamp. You can then use Comparable.compareTo to see whether it's in the ranges you've given.
final DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyMMddHHmmssSSS");
LocalTime time = LocalTime.parse("20180301050630663", formatter);
if (time.compareTo(LocalTime.of(9, 15)) >= 0
&& time.compareTo(LocalTime.of(12, 0)) <= 0)
{
System.out.println("First period");
}
else if (time.compareTo(LocalTime.of(15, 15)) >= 0
&& time.compareTo(LocalTime.of(18, 0 )) <= 0)
{
System.out.println("Second period");
}
If your ranges were exclusive rather than inclusive, you could have used LocalTime.isAfter and LocalTime.isBefore which would have resulted in slightly nicer looking code.
I have some java code that parses a string and creates a Date object. On Linux, everything works fine, but on Windows it continuously starts at 19:00:00 rather than 00:00:00. Here is the code:
if(currTask != null) {
if((m = p0.matcher(currTask)).matches()) {
date = new Date(Long.valueOf(m.group(2)) - Long.valueOf(m.group(1)));
}
else if((m = p.matcher(currTask)).matches()) {
date = new Date(System.currentTimeMillis() - Long.valueOf(m.group(1)));
}
return padded(date.getHours())+":"+padded(date.getMinutes())+":"+padded(date.getSeconds());
}
The returned value is the problem on Windows. Is this some inconsistency with how one of Date's methods works on Windows as opposed to Linux? Thanks for your help.
Ken
Check that your time zone is the same on both platforms... my guess is that they're not. (Print out TimeZone.getDefault().getDisplayName() to see what the default is.)
However, you shouldn't be using Date.getHours()/getMinutes()/getSeconds()/getSeconds() anyway; they're deprecated. You could use Calendar... or you could bite the bullet and use Joda Time, which is a far superior date and time API.
What does your input look like and what's the result meant to be?
The difference must be in your locale. There are environment variables that affect this on Linux. Let me guess: you're in EST (GMT-5)?